Showing preview only (251K chars total). Download the full file or copy to clipboard to get everything.
Repository: deanxv/genspark2api
Branch: main
Commit: 99b038b5f3fa
Files: 47
Total size: 230.1 KB
Directory structure:
gitextract_kz2qbgc6/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ ├── config.yml
│ │ └── feature_request.md
│ ├── close_issue.py
│ └── workflows/
│ ├── CloseIssue.yml
│ ├── docker-image-amd64.yml
│ ├── docker-image-arm64.yml
│ ├── github-pages.yml
│ ├── linux-release.yml
│ ├── macos-release.yml
│ └── windows-release.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── check/
│ └── check.go
├── common/
│ ├── config/
│ │ └── config.go
│ ├── constants.go
│ ├── env/
│ │ └── helper.go
│ ├── helper/
│ │ ├── helper.go
│ │ ├── key.go
│ │ └── time.go
│ ├── init.go
│ ├── loggger/
│ │ ├── constants.go
│ │ └── logger.go
│ ├── random/
│ │ └── main.go
│ ├── rate-limit.go
│ ├── token.go
│ └── utils.go
├── controller/
│ ├── api.go
│ ├── chat.go
│ └── video.go
├── docker-compose.yml
├── go.mod
├── go.sum
├── job/
│ └── cookie.go
├── main.go
├── middleware/
│ ├── auth.go
│ ├── cors.go
│ ├── ip-list.go
│ ├── logger.go
│ ├── rate-limit.go
│ └── request-id.go
├── model/
│ └── openai.go
├── router/
│ ├── api-router.go
│ └── main.go
└── yescaptcha/
└── main.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: 报告问题
about: 使用简练详细的语言描述你遇到的问题
title: ''
labels: bug
assignees: ''
---
**温馨提示: 未`star`项目会被自动关闭issue哦!**
**例行检查**
+ [ ] 我已确认目前没有类似 issue
+ [ ] 我已确认我已升级到最新版本
+ [ ] 我理解并愿意跟进此 issue,协助测试和提供反馈
+ [ ] 我理解并认可上述内容,并理解项目维护者精力有限,不遵循规则的 issue 可能会被无视或直接关闭
**问题描述**
**复现步骤**
**预期结果**
**相关截图**
如果没有的话,请删除此节。
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
- name: 赞赏支持
# url:
about: 请作者喝杯咖啡,以激励作者持续开发
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: 功能请求
about: 使用简练详细的语言描述希望加入的新功能
title: ''
labels: enhancement
assignees: ''
---
**温馨提示: 未`star`项目会被自动关闭issue哦!**
**例行检查**
+ [ ] 我已确认目前没有类似 issue
+ [ ] 我已确认我已升级到最新版本
+ [ ] 我理解并愿意跟进此 issue,协助测试和提供反馈
+ [ ] 我理解并认可上述内容,并理解项目维护者精力有限,不遵循规则的 issue 可能会被无视或直接关闭
**功能描述**
**应用场景**
================================================
FILE: .github/close_issue.py
================================================
import os
import requests
issue_labels = ['no respect']
github_repo = 'deanxv/genspark2api'
github_token = os.getenv("GITHUB_TOKEN")
headers = {
'Authorization': 'Bearer ' + github_token,
'Accept': 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
}
def get_stargazers(repo):
page = 1
_stargazers = {}
while True:
queries = {
'per_page': 100,
'page': page,
}
url = 'https://api.github.com/repos/{}/stargazers?'.format(repo)
resp = requests.get(url, headers=headers, params=queries)
if resp.status_code != 200:
raise Exception('Error get stargazers: ' + resp.text)
data = resp.json()
if not data:
break
for stargazer in data:
_stargazers[stargazer['login']] = True
page += 1
print('list stargazers done, total: ' + str(len(_stargazers)))
return _stargazers
def get_issues(repo):
page = 1
_issues = []
while True:
queries = {
'state': 'open',
'sort': 'created',
'direction': 'desc',
'per_page': 100,
'page': page,
}
url = 'https://api.github.com/repos/{}/issues?'.format(repo)
resp = requests.get(url, headers=headers, params=queries)
if resp.status_code != 200:
raise Exception('Error get issues: ' + resp.text)
data = resp.json()
if not data:
break
_issues += data
page += 1
print('list issues done, total: ' + str(len(_issues)))
return _issues
def close_issue(repo, issue_number):
url = 'https://api.github.com/repos/{}/issues/{}'.format(repo, issue_number)
data = {
'state': 'closed',
'state_reason': 'not_planned',
'labels': issue_labels,
}
resp = requests.patch(url, headers=headers, json=data)
if resp.status_code != 200:
raise Exception('Error close issue: ' + resp.text)
print('issue: {} closed'.format(issue_number))
def lock_issue(repo, issue_number):
url = 'https://api.github.com/repos/{}/issues/{}/lock'.format(repo, issue_number)
data = {
'lock_reason': 'spam',
}
resp = requests.put(url, headers=headers, json=data)
if resp.status_code != 204:
raise Exception('Error lock issue: ' + resp.text)
print('issue: {} locked'.format(issue_number))
if '__main__' == __name__:
stargazers = get_stargazers(github_repo)
issues = get_issues(github_repo)
for issue in issues:
login = issue['user']['login']
if login not in stargazers:
print('issue: {}, login: {} not in stargazers'.format(issue['number'], login))
close_issue(github_repo, issue['number'])
lock_issue(github_repo, issue['number'])
print('done')
================================================
FILE: .github/workflows/CloseIssue.yml
================================================
name: CloseIssue
on:
workflow_dispatch:
issues:
types: [ opened ]
jobs:
run-python-script:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Install Dependencies
run: pip install requests
- name: Run close_issue.py Script
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: python .github/close_issue.py
================================================
FILE: .github/workflows/docker-image-amd64.yml
================================================
name: Publish Docker image (amd64)
on:
push:
tags:
- '*'
workflow_dispatch:
inputs:
name:
description: 'reason'
required: false
jobs:
push_to_registries:
name: Push Docker image to multiple registries
runs-on: ubuntu-latest
environment: github-pages
permissions:
packages: write
contents: read
steps:
- name: Check out the repo
uses: actions/checkout@v3
- name: Save version info
run: |
git describe --tags > VERSION
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Log in to the Container registry
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v4
with:
images: |
deanxv/genspark2api
ghcr.io/${{ github.repository }}
- name: Build and push Docker images
uses: docker/build-push-action@v3
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
================================================
FILE: .github/workflows/docker-image-arm64.yml
================================================
name: Publish Docker image (arm64)
on:
push:
tags:
- '*'
- '!*-alpha*'
workflow_dispatch:
inputs:
name:
description: 'reason'
required: false
jobs:
push_to_registries:
name: Push Docker image to multiple registries
runs-on: ubuntu-latest
environment: github-pages
permissions:
packages: write
contents: read
steps:
- name: Check out the repo
uses: actions/checkout@v3
- name: Save version info
run: |
git describe --tags > VERSION
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Log in to the Container registry
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v4
with:
images: |
deanxv/genspark2api
ghcr.io/${{ github.repository }}
- name: Build and push Docker images
uses: docker/build-push-action@v3
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
================================================
FILE: .github/workflows/github-pages.yml
================================================
name: Build GitHub Pages
on:
workflow_dispatch:
inputs:
name:
description: 'Reason'
required: false
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout 🛎️
uses: actions/checkout@v2 # If you're using actions/checkout@v2 you must set persist-credentials to false in most cases for the deployment to work correctly.
with:
persist-credentials: false
- name: Install and Build 🔧 # This example project is built using npm and outputs the result to the 'build' folder. Replace with the commands required to build your project, or remove this step entirely if your site is pre-built.
env:
CI: ""
run: |
cd web
npm install
npm run build
- name: Deploy 🚀
uses: JamesIves/github-pages-deploy-action@releases/v3
with:
ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}
BRANCH: gh-pages # The branch the action should deploy to.
FOLDER: web/build # The folder the action should deploy.
================================================
FILE: .github/workflows/linux-release.yml
================================================
name: Linux Release
permissions:
contents: write
on:
push:
tags:
- '*'
- '!*-alpha*'
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/setup-node@v3
with:
node-version: 16
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: '>=1.18.0'
- name: Build Backend (amd64)
run: |
go mod download
go build -ldflags "-s -w -X 'genspark2api/common.Version=$(git describe --tags)' -extldflags '-static'" -o genspark2api
- name: Build Backend (arm64)
run: |
sudo apt-get update
sudo apt-get install gcc-aarch64-linux-gnu
CC=aarch64-linux-gnu-gcc CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -X 'genspark2api/common.Version=$(git describe --tags)' -extldflags '-static'" -o genspark2api-arm64
- name: Release
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
with:
files: |
genspark2api
genspark2api-arm64
draft: false
generate_release_notes: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
================================================
FILE: .github/workflows/macos-release.yml
================================================
name: macOS Release
permissions:
contents: write
on:
push:
tags:
- '*'
- '!*-alpha*'
jobs:
release:
runs-on: macos-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/setup-node@v3
with:
node-version: 16
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: '>=1.18.0'
- name: Build Backend
run: |
go mod download
go build -ldflags "-X 'genspark2api/common.Version=$(git describe --tags)'" -o genspark2api-macos
- name: Release
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
with:
files: genspark2api-macos
draft: false
generate_release_notes: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
================================================
FILE: .github/workflows/windows-release.yml
================================================
name: Windows Release
permissions:
contents: write
on:
push:
tags:
- '*'
- '!*-alpha*'
jobs:
release:
runs-on: windows-latest
defaults:
run:
shell: bash
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/setup-node@v3
with:
node-version: 16
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: '>=1.18.0'
- name: Build Backend
run: |
go mod download
go build -ldflags "-s -w -X 'genspark2api/common.Version=$(git describe --tags)'" -o genspark2api.exe
- name: Release
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
with:
files: genspark2api.exe
draft: false
generate_release_notes: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
================================================
FILE: .gitignore
================================================
.idea
.vscode
upload
*.exe
*.db
build
================================================
FILE: Dockerfile
================================================
# 使用 Golang 镜像作为构建阶段
FROM golang AS builder
# 设置环境变量
ENV GO111MODULE=on \
CGO_ENABLED=0 \
GOOS=linux
# 设置工作目录
WORKDIR /build
# 复制 go.mod 和 go.sum 文件,先下载依赖
COPY go.mod go.sum ./
#ENV GOPROXY=https://goproxy.cn,direct
RUN go mod download
# 复制整个项目并构建可执行文件
COPY . .
RUN go build -o /genspark2api
# 使用 Alpine 镜像作为最终镜像
FROM alpine
# 安装基本的运行时依赖
RUN apk --no-cache add ca-certificates tzdata
# 从构建阶段复制可执行文件
COPY --from=builder /genspark2api .
# 暴露端口
EXPOSE 7055
# 工作目录
WORKDIR /app/genspark2api/data
# 设置入口命令
ENTRYPOINT ["/genspark2api"]
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
<p align="right">
<strong>中文</strong>
</p>
<div align="center">
# Genspark2API
_觉得有点意思的话 别忘了点个 ⭐_
<a href="https://t.me/+raL5ppEzDIFmZTY1">
<img src="https://img.shields.io/badge/Telegram-AI Wave交流群-0088cc?style=for-the-badge&logo=telegram&logoColor=white" alt="Telegram 交流群" />
</a>
<sup><i>AI Wave 社群</i></sup> · <sup><i>(群内提供公益API、AI机器人)</i></sup>
</div>
> ⚠️目前官方强制校验`ReCaptchaV3`
> 不通过则模型降智/生图异常,请参考[genspark-playwright-prxoy服务过V3验证](#genspark-playwright-prxoy服务过V3验证)并配置环境变量
`RECAPTCHA_PROXY_URL`。
## 功能
- [x] 支持对话接口(流式/非流式)(`/chat/completions`)(请求非以下列表的模型会触发`Mixture-of-Agents`模式)
- **gpt-5-minimal**
- **gpt-5**
- **gpt-5-high**
- **gpt-5-pro**
- **gpt-4.1**
- **o1**
- **o3**
- **o3-pro**
- **o4-mini-high**
- **claude-3-7-sonnet-thinking**
- **claude-3-7-sonnet**
- **claude-sonnet-4-5**
- **claude-sonnet-4-thinking**
- **claude-sonnet-4**
- **claude-opus-4-1**
- **claude-opus-4**
- **gemini-2.5-pro**
- **gemini-2.5-flash**
- **gemini-2.0-flash**
- **deep-seek-v3**
- **deep-seek-r1**
- **grok-4-0709**
- [x] 支持**联网搜索**,在模型名后添加`-search`即可(如:`gpt-4o-search`)
- [x] 支持识别**图片**/**文件**多轮对话
- [x] 支持文生图接口(`/images/generations`)
- **fal-ai/nano-banana**
- **fal-ai/bytedance/seedream/v4**
- **gpt-image-1**
- **flux-pro/ultra**
- **flux-pro/kontext/pro**
- **imagen4**
- [x] 支持文/图生视频接口(`/videos/generations`),详情查看[文/图生视频请求格式](#生视频请求格式)
- [x] 支持自定义请求头校验值(Authorization)
- [x] 支持cookie池(随机)
- [x] 支持请求失败自动切换cookie重试(需配置cookie池)
- [x] 可配置自动删除对话记录
- [x] 可配置代理请求(环境变量`PROXY_URL`)
- [x] 可配置Model绑定Chat(解决模型自动切换导致**降智**),详细请看[进阶配置](#解决模型自动切换导致降智问题)。
### 接口文档:
略
### 示例:
<span><img src="docs/img2.png" width="800"/></span>
## 如何使用
略
## 如何集成NextChat
填 接口地址(ip:端口/域名) 及 API-Key(`PROXY_SECRET`),其它的随便填随便选。
> 如果自己没有搭建NextChat面板,这里有个已经搭建好的可以使用 [NeatChat](https://ai.aytsao.cn/)
<span><img src="docs/img5.png" width="800"/></span>
## 如何集成one-api
填 `BaseURL`(ip:端口/域名) 及 密钥(`PROXY_SECRET`),其它的随便填随便选。
<span><img src="docs/img3.png" width="800"/></span>
## 部署
### 基于 Docker-Compose(All In One) 进行部署
```shell
docker-compose pull && docker-compose up -d
```
#### docker-compose.yml
```docker
version: '3.4'
services:
genspark2api:
image: deanxv/genspark2api:latest
container_name: genspark2api
restart: always
ports:
- "7055:7055"
volumes:
- ./data:/app/genspark2api/data
environment:
- GS_COOKIE=****** # cookie (多个请以,分隔)
- API_SECRET=123456 # [可选]接口密钥-修改此行为请求头校验的值(多个请以,分隔)
- TZ=Asia/Shanghai
```
### 基于 Docker 进行部署
```docker
docker run --name genspark2api -d --restart always \
-p 7055:7055 \
-v $(pwd)/data:/app/genspark2api/data \
-e GS_COOKIE=***** \
-e API_SECRET="123456" \
-e TZ=Asia/Shanghai \
deanxv/genspark2api
```
其中`API_SECRET`、`GS_COOKIE`修改为自己的。
如果上面的镜像无法拉取,可以尝试使用 GitHub 的 Docker 镜像,将上面的`deanxv/genspark2api`替换为
`ghcr.io/deanxv/genspark2api`即可。
### 部署到第三方平台
<details>
<summary><strong>部署到 Zeabur</strong></summary>
<div>
[](https://zeabur.com?referralCode=deanxv&utm_source=deanxv)
> Zeabur 的服务器在国外,自动解决了网络的问题,~~同时免费的额度也足够个人使用~~
1. 首先 **fork** 一份代码。
2. 进入 [Zeabur](https://zeabur.com?referralCode=deanxv),使用github登录,进入控制台。
3. 在 Service -> Add Service,选择 Git(第一次使用需要先授权),选择你 fork 的仓库。
4. Deploy 会自动开始,先取消。
5. 添加环境变量
`GS_COOKIE:******` cookie (多个请以,分隔)
`API_SECRET:123456` [可选]接口密钥-修改此行为请求头校验的值(多个请以,分隔)(与openai-API-KEY用法一致)
保存。
6. 选择 Redeploy。
</div>
</details>
<details>
<summary><strong>部署到 Render</strong></summary>
<div>
> Render 提供免费额度,绑卡后可以进一步提升额度
Render 可以直接部署 docker 镜像,不需要 fork 仓库:[Render](https://dashboard.render.com)
</div>
</details>
## 配置
### 环境变量
1. `PORT=7055` [可选]端口,默认为7055
2. `DEBUG=true` [可选]DEBUG模式,可打印更多信息[true:打开、false:关闭]
3. `API_SECRET=123456` [可选]接口密钥-修改此行为请求头(Authorization)校验的值(同API-KEY)(多个请以,分隔)
4. `GS_COOKIE=******` cookie (多个请以,分隔)
5. `AUTO_DEL_CHAT=0` [可选]对话完成自动删除(默认:0)[0:关闭,1:开启]
6. `REQUEST_RATE_LIMIT=60` [可选]每分钟下的单ip请求速率限制,默认:60次/min
7. `PROXY_URL=http://127.0.0.1:10801` [可选]代理
8. `RECAPTCHA_PROXY_URL=http://127.0.0.1:7022` [可选]genspark-playwright-prxoy验证服务地址,仅填写域名或ip:端口即可。(
示例:`RECAPTCHA_PROXY_URL=https://genspark-playwright-prxoy.com`或`RECAPTCHA_PROXY_URL=http://127.0.0.1:7022`)
,详情请看[genspark-playwright-prxoy服务过V3验证](#genspark-playwright-prxoy服务过V3验证)
9. `AUTO_MODEL_CHAT_MAP_TYPE=1` [可选]自动配置Model绑定Chat(默认:1)[0:关闭,1:开启]
10. `MODEL_CHAT_MAP=claude-3-7-sonnet=a649******00fa,gpt-4o=su74******47hd` [可选]Model绑定Chat(多个请以,分隔)
,详细请看[进阶配置](#解决模型自动切换导致降智问题)
11. `ROUTE_PREFIX=hf` [可选]路由前缀,默认为空,添加该变量后的接口示例:`/hf/v1/chat/completions`
12. `RATE_LIMIT_COOKIE_LOCK_DURATION=600` [可选]到达速率限制的cookie禁用时间,默认为600s
13. `REASONING_HIDE=0` [可选]**隐藏**推理过程(默认:0)[0:关闭,1:开启]
~~14.
`SESSION_IMAGE_CHAT_MAP=aed9196b-********-4ed6e32f7e4d=0c6785e6-********-7ff6e5a2a29c,aefwer6b-********-casds22=fda234-********-sfaw123` [可选]
Session绑定Image-Chat(多个请以,分隔),详细请看[进阶配置](#生图模型配置)~~
~~15. `YES_CAPTCHA_CLIENT_KEY=******` [可选]YesCaptcha Client Key
过谷歌验证,详细请看[使用YesCaptcha过谷歌验证](#使用YesCaptcha过谷歌验证)~~
### cookie获取方式
1. 打开**F12**开发者工具。
2. 发起对话。
3. 点击ask请求,请求头中的**cookie**即为环境变量**GS_COOKIE**所需值。
> **【注】** 其中`session_id=f9c60******cb6d`是必须的,其他内容可要可不要,即环境变量`GS_COOKIE=session_id=f9c60******cb6d`

## 进阶配置
### 解决模型自动切换导致降智问题
#### 方案一 (默认启用此配置)【推荐】
> 配置环境变量 **AUTO_MODEL_CHAT_MAP_TYPE=1**
>
> 此配置下,会在调用模型时获取对话的id,并绑定模型。
#### 方案二
> 配置环境变量 MODEL_CHAT_MAP
>
> 【作用】指定对话,解决模型自动切换导致降智问题。
1. 打开**F12**开发者工具。
2. 选择需要绑定的对话的模型(示例:`claude-3-7-sonnet`),发起对话。
3. 点击ask请求,此时最上方url中的`id`(或响应中的`id`)即为此对话唯一id。

4. 配置环境变量 `MODEL_CHAT_MAP=claude-3-7-sonnet=3cdcc******474c5` (多个请以,分隔)
### genspark-playwright-prxoy服务过V3验证
1. docker部署genspark-playwright-prxoy
#### docker
```docker
docker run --name genspark-playwright-proxy -d --restart always \
-p 7022:7022 \
-v $(pwd)/data:/app/genspark-playwright-proxy/data \
-e PROXY_URL=http://account:pwd@ip:port # [可选] 推荐(住宅)动态代理,配置代理后过验证概率更高,但响应会变慢。
-e TZ=Asia/Shanghai \
deanxv/genspark-playwright-proxy
```
#### docker-compose
```docker-compose
version: '3.4'
services:
genspark-playwright-prxoy:
image: deanxv/genspark-playwright-proxy:latest
container_name: genspark-playwright-prxoy
restart: always
ports:
- "7022:7022"
volumes:
- ./data:/app/genspark-playwright-prxoy/data
environment:
- PROXY_URL=http://account:pwd@ip:port # [可选] 推荐(住宅)动态代理,配置代理后过验证概率更高,但响应会变慢。
```
2. 部署后配置`genspark2api`环境变量`RECAPTCHA_PROXY_URL`,仅填写域名或ip:端口即可。(示例:
`RECAPTCHA_PROXY_URL=https://genspark-playwright-prxoy.com`或`RECAPTCHA_PROXY_URL=http://127.0.0.1:7022`)
3. 重启`genspark2api`服务。
#### 接入自定义Recaptcha服务
###### 接口:获取令牌
###### 基本信息
- **接口地址**:`/genspark`
- **请求方式**:GET
- **接口描述**:获取用户认证令牌
###### 请求参数
###### 请求头
| 参数名 | 必选 | 类型 | 说明 |
|--------|----|--------|--------|
| cookie | 是 | string | 用户会话凭证 |
###### 响应参数
###### 响应示例
```json
{
"code": 200,
"token": "ey********pe"
}
```
## 报错排查
> `Detected Cloudflare Challenge Page`
>
被Cloudflare拦截出5s盾,可配置`PROXY_URL`。
(【推荐方案】[自建ipv6代理池绕过cf对ip的速率限制及5s盾](https://linux.do/t/topic/367413)
或购买[IProyal](https://iproyal.cn/?r=244330))
> `Genspark Service Unavailable`
>
Genspark官方服务不可用,请稍后再试。
> `All cookies are temporarily unavailable.`
>
所有用户(cookie)均到达速率限制,更换用户cookie或稍后再试。
## 生视频请求格式
### Request
**Endpoint**: `POST /v1/videos/generations`
**Content-Type**: `application/json`
#### Request Parameters
| 字段 Field | 类型 Type | 必填 Required | 描述 Description | 可选值 Accepted Values |
|--------------|---------|-------------|---------------------------|-------------------------------------------------------------------------------------------------|
| model | string | 是 | 使用的视频生成模型 | 模型列表: `sora-2`\|`sora-2-pro`\|`gemini/veo3`\|`gemini/veo3/fast`\|`kling/v2.5-turbo/pro`\|`fal-ai/bytedance/seedance/v1/pro`\|`minimax/hailuo-02/standard`\|`pixverse/v5`\|`fal-ai/bytedance/seedance/v1/lite`\|`gemini/veo2`\|`wan/v2.2`\|`hunyuan`\|`vidu/start-end-to-video`\|`runway/gen4_turbo` |
| aspect_ratio | string | 是 | 视频宽高比 | `9:16` \| `16:9` \| `3:4` \|`1:1` \| `4:3` |
| duration | int | 是 | 视频时长(单位:秒) | 正整数 |
| prompt | string | 是 | 生成视频的文本描述 | - |
| auto_prompt | bool | 是 | 是否自动优化提示词 | `true` \| `false` |
| image | string | 否 | 用于视频生成的基底图片(Base64编码/url) | Base64字符串/url |
---
### Response
#### Response Object
```json
{
"created": 1677664796,
"data": [
{
"url": "https://example.com/video.mp4"
}
]
}
```
## 其他
**Genspark**(
注册领取1个月Plus): [https://www.genspark.ai](https://www.genspark.ai/invite?invite_code=YjVjMGRkYWVMZmE4YUw5MDc0TDM1ODlMZDYwMzQ4OTJlNmEx)
================================================
FILE: check/check.go
================================================
package check
import (
"genspark2api/common"
"genspark2api/common/config"
logger "genspark2api/common/loggger"
"github.com/samber/lo"
"regexp"
"strings"
)
func CheckEnvVariable() {
logger.SysLog("environment variable checking...")
if config.GSCookie == "" {
logger.FatalLog("环境变量 GS_COOKIE 未设置")
}
if config.YesCaptchaClientKey == "" {
//logger.SysLog("环境变量 YES_CAPTCHA_CLIENT_KEY 未设置,将无法使用 YesCaptcha 过谷歌验证,导致无法调用文生图模型 \n ClientKey获取地址:https://yescaptcha.com/i/021iAE")
}
if config.ModelChatMapStr != "" {
pattern := `^([a-zA-Z0-9\-\/]+=([a-zA-Z0-9\-\.]+))(,[a-zA-Z0-9\-\/]+=([a-zA-Z0-9\-\.]+))*`
match, _ := regexp.MatchString(pattern, config.ModelChatMapStr)
if !match {
logger.FatalLog("环境变量 MODEL_CHAT_MAP 设置有误")
} else {
modelChatMap := make(map[string]string)
pairs := strings.Split(config.ModelChatMapStr, ",")
for _, pair := range pairs {
kv := strings.Split(pair, "=")
if !lo.Contains(common.DefaultOpenaiModelList, kv[0]) {
logger.FatalLog("环境变量 MODEL_CHAT_MAP 中 MODEL 有误")
}
modelChatMap[kv[0]] = kv[1]
}
config.ModelChatMap = modelChatMap
if config.AutoModelChatMapType == 1 {
logger.FatalLog("环境变量 MODEL_CHAT_MAP 有值时,环境变量 AUTO_MODEL_CHAT_MAP_TYPE 不能设置为1")
}
}
}
if config.SessionImageChatMapStr != "" {
pattern := `^([a-zA-Z0-9\-\/]+=([a-zA-Z0-9\-\.]+))(,[a-zA-Z0-9\-\/]+=([a-zA-Z0-9\-\.]+))*`
match, _ := regexp.MatchString(pattern, config.SessionImageChatMapStr)
if !match {
logger.FatalLog("环境变量 SESSION_IMAGE_CHAT_MAP 设置有误")
} else {
sessionImageChatMap := make(map[string]string)
pairs := strings.Split(config.SessionImageChatMapStr, ",")
for _, pair := range pairs {
kv := strings.Split(pair, "=")
sessionImageChatMap["session_id="+kv[0]] = kv[1]
}
config.SessionImageChatMap = sessionImageChatMap
}
} else {
//logger.SysLog("环境变量 SESSION_IMAGE_CHAT_MAP 未设置,生图可能会异常")
}
logger.SysLog("environment variable check passed.")
}
================================================
FILE: common/config/config.go
================================================
package config
import (
"errors"
"genspark2api/common/env"
"genspark2api/yescaptcha"
"math/rand"
"os"
"strings"
"sync"
"time"
)
var ApiSecret = os.Getenv("API_SECRET")
var ApiSecrets = strings.Split(os.Getenv("API_SECRET"), ",")
var GSCookie = os.Getenv("GS_COOKIE")
//var GSCookies = strings.Split(os.Getenv("GS_COOKIE"), ",")
// var IpBlackList = os.Getenv("IP_BLACK_LIST")
var IpBlackList = strings.Split(os.Getenv("IP_BLACK_LIST"), ",")
var AutoDelChat = env.Int("AUTO_DEL_CHAT", 0)
var ProxyUrl = env.String("PROXY_URL", "")
var AutoModelChatMapType = env.Int("AUTO_MODEL_CHAT_MAP_TYPE", 1)
var YesCaptchaClientKey = env.String("YES_CAPTCHA_CLIENT_KEY", "")
// var CheatUrl = env.String("CHEAT_URL", "https://gs-cheat.aytsao.cn/genspark/create/req/body")
var RecaptchaProxyUrl = env.String("RECAPTCHA_PROXY_URL", "")
// 隐藏思考过程
var ReasoningHide = env.Int("REASONING_HIDE", 0)
// 前置message
var PRE_MESSAGES_JSON = env.String("PRE_MESSAGES_JSON", "")
var RateLimitCookieLockDuration = env.Int("RATE_LIMIT_COOKIE_LOCK_DURATION", 10*60)
// 路由前缀
var RoutePrefix = env.String("ROUTE_PREFIX", "")
var ModelChatMapStr = env.String("MODEL_CHAT_MAP", "")
var ModelChatMap = make(map[string]string)
var SessionImageChatMap = make(map[string]string)
var GlobalSessionManager *SessionManager
var SessionImageChatMapStr = env.String("SESSION_IMAGE_CHAT_MAP", "")
var YescaptchaClient *yescaptcha.Client
var AllDialogRecordEnable = os.Getenv("ALL_DIALOG_RECORD_ENABLE")
var RequestOutTime = os.Getenv("REQUEST_OUT_TIME")
var StreamRequestOutTime = os.Getenv("STREAM_REQUEST_OUT_TIME")
var SwaggerEnable = os.Getenv("SWAGGER_ENABLE")
var OnlyOpenaiApi = os.Getenv("ONLY_OPENAI_API")
var DebugEnabled = os.Getenv("DEBUG") == "true"
var RateLimitKeyExpirationDuration = 20 * time.Minute
var RequestOutTimeDuration = 5 * time.Minute
var (
RequestRateLimitNum = env.Int("REQUEST_RATE_LIMIT", 60)
RequestRateLimitDuration int64 = 1 * 60
)
type RateLimitCookie struct {
ExpirationTime time.Time // 过期时间
}
var (
rateLimitCookies sync.Map // 使用 sync.Map 管理限速 Cookie
)
func AddRateLimitCookie(cookie string, expirationTime time.Time) {
rateLimitCookies.Store(cookie, RateLimitCookie{
ExpirationTime: expirationTime,
})
//fmt.Printf("Storing cookie: %s with value: %+v\n", cookie, RateLimitCookie{ExpirationTime: expirationTime})
}
type CookieManager struct {
Cookies []string
currentIndex int
mu sync.Mutex
}
var (
GSCookies []string // 存储所有的 cookies
cookiesMutex sync.Mutex // 保护 GSCookies 的互斥锁
)
// InitGSCookies 初始化 GSCookies
func InitGSCookies() {
cookiesMutex.Lock()
defer cookiesMutex.Unlock()
GSCookies = []string{}
// 从环境变量中读取 GS_COOKIE 并拆分为切片
cookieStr := os.Getenv("GS_COOKIE")
if cookieStr != "" {
for _, cookie := range strings.Split(cookieStr, ",") {
// 如果 cookie 不包含 "session_id=",则添加前缀
if !strings.Contains(cookie, "session_id=") {
cookie = "session_id=" + cookie
}
GSCookies = append(GSCookies, cookie)
}
}
}
// RemoveCookie 删除指定的 cookie(支持并发)
func RemoveCookie(cookieToRemove string) {
cookiesMutex.Lock()
defer cookiesMutex.Unlock()
// 创建一个新的切片,过滤掉需要删除的 cookie
var newCookies []string
for _, cookie := range GetGSCookies() {
if cookie != cookieToRemove {
newCookies = append(newCookies, cookie)
}
}
// 更新 GSCookies
GSCookies = newCookies
}
// GetGSCookies 获取 GSCookies 的副本
func GetGSCookies() []string {
//cookiesMutex.Lock()
//defer cookiesMutex.Unlock()
// 返回 GSCookies 的副本,避免外部直接修改
cookiesCopy := make([]string, len(GSCookies))
copy(cookiesCopy, GSCookies)
return cookiesCopy
}
// NewCookieManager 创建 CookieManager
func NewCookieManager() *CookieManager {
var validCookies []string
// 遍历 GSCookies
for _, cookie := range GetGSCookies() {
cookie = strings.TrimSpace(cookie)
if cookie == "" {
continue // 忽略空字符串
}
// 检查是否在 RateLimitCookies 中
if value, ok := rateLimitCookies.Load(cookie); ok {
rateLimitCookie, ok := value.(RateLimitCookie) // 正确转换为 RateLimitCookie
if !ok {
continue
}
if rateLimitCookie.ExpirationTime.After(time.Now()) {
// 如果未过期,忽略该 cookie
continue
} else {
// 如果已过期,从 RateLimitCookies 中删除
rateLimitCookies.Delete(cookie)
}
}
// 添加到有效 cookie 列表
validCookies = append(validCookies, cookie)
}
return &CookieManager{
Cookies: validCookies,
currentIndex: 0,
}
}
func IsRateLimited(cookie string) bool {
if value, ok := rateLimitCookies.Load(cookie); ok {
rateLimitCookie := value.(RateLimitCookie)
return rateLimitCookie.ExpirationTime.After(time.Now())
}
return false
}
func (cm *CookieManager) RemoveCookie(cookieToRemove string) error {
cm.mu.Lock()
defer cm.mu.Unlock()
if len(cm.Cookies) == 0 {
return errors.New("no cookies available")
}
// 查找要删除的cookie的索引
index := -1
for i, cookie := range cm.Cookies {
if cookie == cookieToRemove {
index = i
break
}
}
// 如果没找到要删除的cookie
if index == -1 {
return errors.New("RemoveCookie -> cookie not found")
}
// 从切片中删除cookie
cm.Cookies = append(cm.Cookies[:index], cm.Cookies[index+1:]...)
// 如果当前索引大于或等于删除后的切片长度,重置为0
if cm.currentIndex >= len(cm.Cookies) {
cm.currentIndex = 0
}
return nil
}
func (cm *CookieManager) GetNextCookie() (string, error) {
cm.mu.Lock()
defer cm.mu.Unlock()
if len(cm.Cookies) == 0 {
return "", errors.New("no cookies available")
}
cm.currentIndex = (cm.currentIndex + 1) % len(cm.Cookies)
return cm.Cookies[cm.currentIndex], nil
}
func (cm *CookieManager) GetRandomCookie() (string, error) {
cm.mu.Lock()
defer cm.mu.Unlock()
if len(cm.Cookies) == 0 {
return "", errors.New("no cookies available")
}
// 生成随机索引
randomIndex := rand.Intn(len(cm.Cookies))
// 更新当前索引
cm.currentIndex = randomIndex
return cm.Cookies[randomIndex], nil
}
// SessionKey 定义复合键结构
type SessionKey struct {
Cookie string
Model string
}
// SessionManager 会话管理器
type SessionManager struct {
sessions map[SessionKey]string
mutex sync.RWMutex
}
// NewSessionManager 创建新的会话管理器
func NewSessionManager() *SessionManager {
return &SessionManager{
sessions: make(map[SessionKey]string),
}
}
// AddSession 添加会话记录(写操作,需要写锁)
func (sm *SessionManager) AddSession(cookie string, model string, chatID string) {
sm.mutex.Lock()
defer sm.mutex.Unlock()
key := SessionKey{
Cookie: cookie,
Model: model,
}
sm.sessions[key] = chatID
}
// GetChatID 获取会话ID(读操作,使用读锁)
func (sm *SessionManager) GetChatID(cookie string, model string) (string, bool) {
sm.mutex.RLock()
defer sm.mutex.RUnlock()
key := SessionKey{
Cookie: cookie,
Model: model,
}
chatID, exists := sm.sessions[key]
return chatID, exists
}
// DeleteSession 删除会话记录(写操作,需要写锁)
func (sm *SessionManager) DeleteSession(cookie string, model string) {
sm.mutex.Lock()
defer sm.mutex.Unlock()
key := SessionKey{
Cookie: cookie,
Model: model,
}
delete(sm.sessions, key)
}
// GetChatIDsByCookie 获取指定cookie关联的所有chatID列表(读操作,使用读锁)
func (sm *SessionManager) GetChatIDsByCookie(cookie string) []string {
sm.mutex.RLock()
defer sm.mutex.RUnlock()
var chatIDs []string
for key, chatID := range sm.sessions {
if key.Cookie == cookie {
chatIDs = append(chatIDs, chatID)
}
}
return chatIDs
}
type SessionMapManager struct {
sessionMap map[string]string
keys []string
currentIndex int
mu sync.Mutex
}
func NewSessionMapManager() *SessionMapManager {
// 从初始map中提取所有的key
keys := make([]string, 0, len(SessionImageChatMap))
for k := range SessionImageChatMap {
keys = append(keys, k)
}
return &SessionMapManager{
sessionMap: SessionImageChatMap,
keys: keys,
currentIndex: 0,
}
}
// GetCurrentKeyValue 获取当前索引对应的键值对
func (sm *SessionMapManager) GetCurrentKeyValue() (string, string, error) {
sm.mu.Lock()
defer sm.mu.Unlock()
if len(sm.keys) == 0 {
return "", "", errors.New("no sessions available")
}
currentKey := sm.keys[sm.currentIndex]
return currentKey, sm.sessionMap[currentKey], nil
}
// GetNextKeyValue 获取下一个键值对
func (sm *SessionMapManager) GetNextKeyValue() (string, string, error) {
sm.mu.Lock()
defer sm.mu.Unlock()
if len(sm.keys) == 0 {
return "", "", errors.New("no sessions available")
}
sm.currentIndex = (sm.currentIndex + 1) % len(sm.keys)
currentKey := sm.keys[sm.currentIndex]
return currentKey, sm.sessionMap[currentKey], nil
}
// GetRandomKeyValue 随机获取一个键值对
func (sm *SessionMapManager) GetRandomKeyValue() (string, string, error) {
sm.mu.Lock()
defer sm.mu.Unlock()
if len(sm.keys) == 0 {
return "", "", errors.New("no sessions available")
}
randomIndex := rand.Intn(len(sm.keys))
sm.currentIndex = randomIndex
currentKey := sm.keys[randomIndex]
return currentKey, sm.sessionMap[currentKey], nil
}
// AddKeyValue 添加新的键值对
func (sm *SessionMapManager) AddKeyValue(key, value string) {
sm.mu.Lock()
defer sm.mu.Unlock()
// 如果key不存在,则添加到keys切片中
if _, exists := sm.sessionMap[key]; !exists {
sm.keys = append(sm.keys, key)
}
sm.sessionMap[key] = value
}
// RemoveKey 删除指定的键值对
func (sm *SessionMapManager) RemoveKey(key string) {
sm.mu.Lock()
defer sm.mu.Unlock()
if _, exists := sm.sessionMap[key]; !exists {
return
}
// 从map中删除
delete(sm.sessionMap, key)
// 从keys切片中删除
for i, k := range sm.keys {
if k == key {
sm.keys = append(sm.keys[:i], sm.keys[i+1:]...)
break
}
}
// 调整currentIndex如果需要
if sm.currentIndex >= len(sm.keys) && len(sm.keys) > 0 {
sm.currentIndex = len(sm.keys) - 1
}
}
// GetSize 获取当前map的大小
func (sm *SessionMapManager) GetSize() int {
sm.mu.Lock()
defer sm.mu.Unlock()
return len(sm.keys)
}
================================================
FILE: common/constants.go
================================================
package common
import "time"
var StartTime = time.Now().Unix() // unit: second
var Version = "v1.12.6" // this hard coding will be replaced automatically when building, no need to manually change
var DefaultOpenaiModelList = []string{
"gpt-5-pro",
"gpt-5.1-low",
"gpt-5.2",
"gpt-5.2-pro",
"o3-pro",
"claude-sonnet-4-6",
"claude-sonnet-4-5",
"claude-opus-4-6",
"claude-opus-4-5",
"claude-4-5-haiku",
"gemini-2.5-pro",
"gemini-3-flash-preview",
"gemini-3.1-pro-preview",
"gemini-3-pro-preview",
"grok-4-0709",
"nano-banana-pro",
"nano-banana-2",
"fal-ai/bytedance/seedream/v5/lite",
"fal-ai/flux-2",
"fal-ai/flux-2-pro",
"fal-ai/z-image/turbo",
"fal-ai/gpt-image-1.5",
"recraft-v3",
"ideogram/V_3",
"qwen-image",
"fal-ai/recraft-clarity-upscale",
"fal-bria-rmbg",
"fal-ai/image-editing/text-removal",
"gemini/veo3.1",
"gemini/veo3.1/reference-to-video",
"gemini/veo3.1/first-last-frame-to-video",
"sora-2",
"sora-2-pro",
"gemini/veo3",
"kling/v3",
"kling/v2.6/standard/motion-control",
"kling/o3/image-to-video",
"kling/o3/reference-to-video",
"fal-ai/bytedance/seedance/v1.5/pro",
"xai/grok-imagine-video",
"minimax/hailuo-2.3/standard",
"official/pixverse/v5",
"fal-ai/bytedance/seedance/v1/pro/fast",
"fal-ai/sync-lipsync/v2",
"wan/v2.6",
"vidu/q3",
"runway/gen4_turbo",
"fal-ai/bytedance-upscaler/upscale/video",
}
var TextModelList = []string{
"gpt-5-pro",
"gpt-5.1-low",
"gpt-5.2",
"gpt-5.2-pro",
"o3-pro",
"claude-sonnet-4-6",
"claude-sonnet-4-5",
"claude-opus-4-6",
"claude-opus-4-5",
"claude-4-5-haiku",
"gemini-2.5-pro",
"gemini-3-flash-preview",
"gemini-3.1-pro-preview",
"gemini-3-pro-preview",
"grok-4-0709",
}
var MixtureModelList = []string{
"gpt-5.1-low",
"claude-sonnet-4-5",
"gemini-3-pro-preview",
}
var ImageModelList = []string{
"nano-banana-pro",
"nano-banana-2",
"fal-ai/bytedance/seedream/v5/lite",
"fal-ai/flux-2",
"fal-ai/flux-2-pro",
"fal-ai/z-image/turbo",
"fal-ai/gpt-image-1.5",
"recraft-v3",
"ideogram/V_3",
"qwen-image",
"fal-ai/recraft-clarity-upscale",
"fal-bria-rmbg",
"fal-ai/image-editing/text-removal",
}
var VideoModelList = []string{
"gemini/veo3.1",
"gemini/veo3.1/reference-to-video",
"gemini/veo3.1/first-last-frame-to-video",
"sora-2",
"sora-2-pro",
"gemini/veo3",
"kling/v3",
"kling/v2.6/standard/motion-control",
"kling/o3/image-to-video",
"kling/o3/reference-to-video",
"fal-ai/bytedance/seedance/v1.5/pro",
"xai/grok-imagine-video",
"minimax/hailuo-2.3/standard",
"official/pixverse/v5",
"fal-ai/bytedance/seedance/v1/pro/fast",
"fal-ai/sync-lipsync/v2",
"wan/v2.6",
"vidu/q3",
"runway/gen4_turbo",
"fal-ai/bytedance-upscaler/upscale/video",
}
//
================================================
FILE: common/env/helper.go
================================================
package env
import (
"os"
"strconv"
)
func Bool(env string, defaultValue bool) bool {
if env == "" || os.Getenv(env) == "" {
return defaultValue
}
return os.Getenv(env) == "true"
}
func Int(env string, defaultValue int) int {
if env == "" || os.Getenv(env) == "" {
return defaultValue
}
num, err := strconv.Atoi(os.Getenv(env))
if err != nil {
return defaultValue
}
return num
}
func Float64(env string, defaultValue float64) float64 {
if env == "" || os.Getenv(env) == "" {
return defaultValue
}
num, err := strconv.ParseFloat(os.Getenv(env), 64)
if err != nil {
return defaultValue
}
return num
}
func String(env string, defaultValue string) string {
if env == "" || os.Getenv(env) == "" {
return defaultValue
}
return os.Getenv(env)
}
================================================
FILE: common/helper/helper.go
================================================
package helper
import (
"fmt"
"genspark2api/common/random"
"github.com/gin-gonic/gin"
"html/template"
"log"
"net"
"os/exec"
"runtime"
"strconv"
"strings"
)
func OpenBrowser(url string) {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
}
if err != nil {
log.Println(err)
}
}
func GetIp() (ip string) {
ips, err := net.InterfaceAddrs()
if err != nil {
log.Println(err)
return ip
}
for _, a := range ips {
if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
ip = ipNet.IP.String()
if strings.HasPrefix(ip, "10") {
return
}
if strings.HasPrefix(ip, "172") {
return
}
if strings.HasPrefix(ip, "192.168") {
return
}
ip = ""
}
}
}
return
}
var sizeKB = 1024
var sizeMB = sizeKB * 1024
var sizeGB = sizeMB * 1024
func Bytes2Size(num int64) string {
numStr := ""
unit := "B"
if num/int64(sizeGB) > 1 {
numStr = fmt.Sprintf("%.2f", float64(num)/float64(sizeGB))
unit = "GB"
} else if num/int64(sizeMB) > 1 {
numStr = fmt.Sprintf("%d", int(float64(num)/float64(sizeMB)))
unit = "MB"
} else if num/int64(sizeKB) > 1 {
numStr = fmt.Sprintf("%d", int(float64(num)/float64(sizeKB)))
unit = "KB"
} else {
numStr = fmt.Sprintf("%d", num)
}
return numStr + " " + unit
}
func Interface2String(inter interface{}) string {
switch inter := inter.(type) {
case string:
return inter
case int:
return fmt.Sprintf("%d", inter)
case float64:
return fmt.Sprintf("%f", inter)
}
return "Not Implemented"
}
func UnescapeHTML(x string) interface{} {
return template.HTML(x)
}
func IntMax(a int, b int) int {
if a >= b {
return a
} else {
return b
}
}
func GenRequestID() string {
return GetTimeString() + random.GetRandomNumberString(8)
}
func GetResponseID(c *gin.Context) string {
logID := c.GetString(RequestIdKey)
return fmt.Sprintf("chatcmpl-%s", logID)
}
func Max(a int, b int) int {
if a >= b {
return a
} else {
return b
}
}
func AssignOrDefault(value string, defaultValue string) string {
if len(value) != 0 {
return value
}
return defaultValue
}
func MessageWithRequestId(message string, id string) string {
return fmt.Sprintf("%s (request id: %s)", message, id)
}
func String2Int(str string) int {
num, err := strconv.Atoi(str)
if err != nil {
return 0
}
return num
}
================================================
FILE: common/helper/key.go
================================================
package helper
const (
RequestIdKey = "X-Request-Id"
)
================================================
FILE: common/helper/time.go
================================================
package helper
import (
"fmt"
"time"
)
func GetTimestamp() int64 {
return time.Now().Unix()
}
func GetTimeString() string {
now := time.Now()
return fmt.Sprintf("%s%d", now.Format("20060102150405"), now.UnixNano()%1e9)
}
================================================
FILE: common/init.go
================================================
package common
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
)
var (
Port = flag.Int("port", 7055, "the listening port")
PrintVersion = flag.Bool("version", false, "print version and exit")
PrintHelp = flag.Bool("help", false, "print help and exit")
LogDir = flag.String("log-dir", "", "specify the log directory")
)
// UploadPath Maybe override by ENV_VAR
var UploadPath = "upload"
func printHelp() {
fmt.Println("genspark2api" + Version + "")
fmt.Println("Copyright (C) 2024 Dean. All rights reserved.")
fmt.Println("GitHub: https://github.com/deanxv/genspark2api ")
fmt.Println("Usage: genspark2api [--port <port>] [--log-dir <log directory>] [--version] [--help]")
}
func init() {
flag.Parse()
if *PrintVersion {
fmt.Println(Version)
os.Exit(0)
}
if *PrintHelp {
printHelp()
os.Exit(0)
}
if os.Getenv("UPLOAD_PATH") != "" {
UploadPath = os.Getenv("UPLOAD_PATH")
}
if *LogDir != "" {
var err error
*LogDir, err = filepath.Abs(*LogDir)
if err != nil {
log.Fatal(err)
}
if _, err := os.Stat(*LogDir); os.IsNotExist(err) {
err = os.Mkdir(*LogDir, 0777)
if err != nil {
log.Fatal(err)
}
}
}
}
================================================
FILE: common/loggger/constants.go
================================================
package logger
var LogDir string
================================================
FILE: common/loggger/logger.go
================================================
package logger
import (
"context"
"fmt"
"genspark2api/common/config"
"genspark2api/common/helper"
"io"
"log"
"os"
"path/filepath"
"sync"
"time"
"github.com/gin-gonic/gin"
)
const (
loggerDEBUG = "DEBUG"
loggerINFO = "INFO"
loggerWarn = "WARN"
loggerError = "ERR"
)
var setupLogOnce sync.Once
func SetupLogger() {
setupLogOnce.Do(func() {
if LogDir != "" {
logPath := filepath.Join(LogDir, fmt.Sprintf("genspark2api-%s.log", time.Now().Format("20060102")))
fd, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal("failed to open log file")
}
gin.DefaultWriter = io.MultiWriter(os.Stdout, fd)
gin.DefaultErrorWriter = io.MultiWriter(os.Stderr, fd)
}
})
}
func SysLog(s string) {
t := time.Now()
_, _ = fmt.Fprintf(gin.DefaultWriter, "[SYS] %v | %s \n", t.Format("2006/01/02 - 15:04:05"), s)
}
func SysError(s string) {
t := time.Now()
_, _ = fmt.Fprintf(gin.DefaultErrorWriter, "[SYS] %v | %s \n", t.Format("2006/01/02 - 15:04:05"), s)
}
func Debug(ctx context.Context, msg string) {
if config.DebugEnabled {
logHelper(ctx, loggerDEBUG, msg)
}
}
func Info(ctx context.Context, msg string) {
logHelper(ctx, loggerINFO, msg)
}
func Warn(ctx context.Context, msg string) {
logHelper(ctx, loggerWarn, msg)
}
func Error(ctx context.Context, msg string) {
logHelper(ctx, loggerError, msg)
}
func Debugf(ctx context.Context, format string, a ...any) {
Debug(ctx, fmt.Sprintf(format, a...))
}
func Infof(ctx context.Context, format string, a ...any) {
Info(ctx, fmt.Sprintf(format, a...))
}
func Warnf(ctx context.Context, format string, a ...any) {
Warn(ctx, fmt.Sprintf(format, a...))
}
func Errorf(ctx context.Context, format string, a ...any) {
Error(ctx, fmt.Sprintf(format, a...))
}
func logHelper(ctx context.Context, level string, msg string) {
writer := gin.DefaultErrorWriter
if level == loggerINFO {
writer = gin.DefaultWriter
}
id := ctx.Value(helper.RequestIdKey)
if id == nil {
id = helper.GenRequestID()
}
now := time.Now()
_, _ = fmt.Fprintf(writer, "[%s] %v | %s | %s \n", level, now.Format("2006/01/02 - 15:04:05"), id, msg)
SetupLogger()
}
func FatalLog(v ...any) {
t := time.Now()
_, _ = fmt.Fprintf(gin.DefaultErrorWriter, "[FATAL] %v | %v \n", t.Format("2006/01/02 - 15:04:05"), v)
os.Exit(1)
}
================================================
FILE: common/random/main.go
================================================
package random
import (
"github.com/google/uuid"
"math/rand"
"strings"
"time"
)
func GetUUID() string {
code := uuid.New().String()
code = strings.Replace(code, "-", "", -1)
return code
}
const keyChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const keyNumbers = "0123456789"
func init() {
rand.Seed(time.Now().UnixNano())
}
func GenerateKey() string {
rand.Seed(time.Now().UnixNano())
key := make([]byte, 48)
for i := 0; i < 16; i++ {
key[i] = keyChars[rand.Intn(len(keyChars))]
}
uuid_ := GetUUID()
for i := 0; i < 32; i++ {
c := uuid_[i]
if i%2 == 0 && c >= 'a' && c <= 'z' {
c = c - 'a' + 'A'
}
key[i+16] = c
}
return string(key)
}
func GetRandomString(length int) string {
rand.Seed(time.Now().UnixNano())
key := make([]byte, length)
for i := 0; i < length; i++ {
key[i] = keyChars[rand.Intn(len(keyChars))]
}
return string(key)
}
func GetRandomNumberString(length int) string {
rand.Seed(time.Now().UnixNano())
key := make([]byte, length)
for i := 0; i < length; i++ {
key[i] = keyNumbers[rand.Intn(len(keyNumbers))]
}
return string(key)
}
// RandRange returns a random number between min and max (max is not included)
func RandRange(min, max int) int {
return min + rand.Intn(max-min)
}
================================================
FILE: common/rate-limit.go
================================================
package common
import (
"sync"
"time"
)
type InMemoryRateLimiter struct {
store map[string]*[]int64
mutex sync.Mutex
expirationDuration time.Duration
}
func (l *InMemoryRateLimiter) Init(expirationDuration time.Duration) {
if l.store == nil {
l.mutex.Lock()
if l.store == nil {
l.store = make(map[string]*[]int64)
l.expirationDuration = expirationDuration
if expirationDuration > 0 {
go l.clearExpiredItems()
}
}
l.mutex.Unlock()
}
}
func (l *InMemoryRateLimiter) clearExpiredItems() {
for {
time.Sleep(l.expirationDuration)
l.mutex.Lock()
now := time.Now().Unix()
for key := range l.store {
queue := l.store[key]
size := len(*queue)
if size == 0 || now-(*queue)[size-1] > int64(l.expirationDuration.Seconds()) {
delete(l.store, key)
}
}
l.mutex.Unlock()
}
}
// Request parameter duration's unit is seconds
func (l *InMemoryRateLimiter) Request(key string, maxRequestNum int, duration int64) bool {
l.mutex.Lock()
defer l.mutex.Unlock()
// [old <-- new]
queue, ok := l.store[key]
now := time.Now().Unix()
if ok {
if len(*queue) < maxRequestNum {
*queue = append(*queue, now)
return true
} else {
if now-(*queue)[0] >= duration {
*queue = (*queue)[1:]
*queue = append(*queue, now)
return true
} else {
return false
}
}
} else {
s := make([]int64, 0, maxRequestNum)
l.store[key] = &s
*(l.store[key]) = append(*(l.store[key]), now)
}
return true
}
================================================
FILE: common/token.go
================================================
package common
import (
"errors"
"fmt"
logger "genspark2api/common/loggger"
"genspark2api/model"
"github.com/pkoukk/tiktoken-go"
"strings"
)
// tokenEncoderMap won't grow after initialization
var tokenEncoderMap = map[string]*tiktoken.Tiktoken{}
var defaultTokenEncoder *tiktoken.Tiktoken
func InitTokenEncoders() {
logger.SysLog("initializing token encoders...")
gpt35TokenEncoder, err := tiktoken.EncodingForModel("gpt-3.5-turbo")
if err != nil {
logger.FatalLog(fmt.Sprintf("failed to get gpt-3.5-turbo token encoder: %s", err.Error()))
}
defaultTokenEncoder = gpt35TokenEncoder
gpt4oTokenEncoder, err := tiktoken.EncodingForModel("gpt-4o")
if err != nil {
logger.FatalLog(fmt.Sprintf("failed to get gpt-4o token encoder: %s", err.Error()))
}
gpt4TokenEncoder, err := tiktoken.EncodingForModel("gpt-4")
if err != nil {
logger.FatalLog(fmt.Sprintf("failed to get gpt-4 token encoder: %s", err.Error()))
}
for _, model := range DefaultOpenaiModelList {
if strings.HasPrefix(model, "gpt-3.5") {
tokenEncoderMap[model] = gpt35TokenEncoder
} else if strings.HasPrefix(model, "gpt-4o") {
tokenEncoderMap[model] = gpt4oTokenEncoder
} else if strings.HasPrefix(model, "gpt-4") {
tokenEncoderMap[model] = gpt4TokenEncoder
} else {
tokenEncoderMap[model] = nil
}
}
logger.SysLog("token encoders initialized.")
}
func getTokenEncoder(model string) *tiktoken.Tiktoken {
tokenEncoder, ok := tokenEncoderMap[model]
if ok && tokenEncoder != nil {
return tokenEncoder
}
if ok {
tokenEncoder, err := tiktoken.EncodingForModel(model)
if err != nil {
//logger.SysError(fmt.Sprintf("[IGNORE] | failed to get token encoder for model %s: %s, using encoder for gpt-3.5-turbo", model, err.Error()))
tokenEncoder = defaultTokenEncoder
}
tokenEncoderMap[model] = tokenEncoder
return tokenEncoder
}
return defaultTokenEncoder
}
func getTokenNum(tokenEncoder *tiktoken.Tiktoken, text string) int {
return len(tokenEncoder.Encode(text, nil, nil))
}
func CountTokenMessages(messages []model.OpenAIChatMessage, model string) int {
tokenEncoder := getTokenEncoder(model)
// Reference:
// https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
// https://github.com/pkoukk/tiktoken-go/issues/6
//
// Every message follows <|start|>{role/name}\n{content}<|end|>\n
var tokensPerMessage int
if model == "gpt-3.5-turbo-0301" {
tokensPerMessage = 4
} else {
tokensPerMessage = 3
}
tokenNum := 0
for _, message := range messages {
tokenNum += tokensPerMessage
switch v := message.Content.(type) {
case string:
tokenNum += getTokenNum(tokenEncoder, v)
case []any:
for _, it := range v {
m := it.(map[string]any)
switch m["type"] {
case "text":
if textValue, ok := m["text"]; ok {
if textString, ok := textValue.(string); ok {
tokenNum += getTokenNum(tokenEncoder, textString)
}
}
case "image_url":
imageUrl, ok := m["image_url"].(map[string]any)
if ok {
url := imageUrl["url"].(string)
detail := ""
if imageUrl["detail"] != nil {
detail = imageUrl["detail"].(string)
}
imageTokens, err := countImageTokens(url, detail, model)
if err != nil {
logger.SysError("error counting image tokens: " + err.Error())
} else {
tokenNum += imageTokens
}
}
}
}
}
tokenNum += getTokenNum(tokenEncoder, message.Role)
}
tokenNum += 3 // Every reply is primed with <|start|>assistant<|message|>
return tokenNum
}
const (
lowDetailCost = 85
highDetailCostPerTile = 170
additionalCost = 85
// gpt-4o-mini cost higher than other model
gpt4oMiniLowDetailCost = 2833
gpt4oMiniHighDetailCost = 5667
gpt4oMiniAdditionalCost = 2833
)
// https://platform.openai.com/docs/guides/vision/calculating-costs
// https://github.com/openai/openai-cookbook/blob/05e3f9be4c7a2ae7ecf029a7c32065b024730ebe/examples/How_to_count_tokens_with_tiktoken.ipynb
func countImageTokens(url string, detail string, model string) (_ int, err error) {
// Reference: https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding
// detail == "auto" is undocumented on how it works, it just said the model will use the auto setting which will look at the image input size and decide if it should use the low or high setting.
// According to the official guide, "low" disable the high-res model,
// and only receive low-res 512px x 512px version of the image, indicating
// that image is treated as low-res when size is smaller than 512px x 512px,
// then we can assume that image size larger than 512px x 512px is treated
// as high-res. Then we have the following logic:
// if detail == "" || detail == "auto" {
// width, height, err = image.GetImageSize(url)
// if err != nil {
// return 0, err
// }
// fetchSize = false
// // not sure if this is correct
// if width > 512 || height > 512 {
// detail = "high"
// } else {
// detail = "low"
// }
// }
// However, in my test, it seems to be always the same as "high".
// The following image, which is 125x50, is still treated as high-res, taken
// 255 tokens in the response of non-stream chat completion api.
// https://upload.wikimedia.org/wikipedia/commons/1/10/18_Infantry_Division_Messina.jpg
if detail == "" || detail == "auto" {
// assume by test, not sure if this is correct
detail = "low"
}
switch detail {
case "low":
if strings.HasPrefix(model, "gpt-4o-mini") {
return gpt4oMiniLowDetailCost, nil
}
return lowDetailCost, nil
default:
return 0, errors.New("invalid detail option")
}
}
func CountTokenInput(input any, model string) int {
switch v := input.(type) {
case string:
return CountTokenText(v, model)
case []string:
text := ""
for _, s := range v {
text += s
}
return CountTokenText(text, model)
}
return 0
}
func CountTokenText(text string, model string) int {
tokenEncoder := getTokenEncoder(model)
return getTokenNum(tokenEncoder, text)
}
func CountToken(text string) int {
return CountTokenInput(text, "gpt-3.5-turbo")
}
================================================
FILE: common/utils.go
================================================
package common
import (
"encoding/base64"
"fmt"
"github.com/google/uuid"
jsoniter "github.com/json-iterator/go"
_ "github.com/pkoukk/tiktoken-go"
"math/rand"
"regexp"
"strings"
"time"
"unicode/utf8"
)
// splitStringByBytes 将字符串按照指定的字节数进行切割
func SplitStringByBytes(s string, size int) []string {
var result []string
for len(s) > 0 {
// 初始切割点
l := size
if l > len(s) {
l = len(s)
}
// 确保不在字符中间切割
for l > 0 && !utf8.ValidString(s[:l]) {
l--
}
// 如果 l 减到 0,说明 size 太小,无法容纳一个完整的字符
if l == 0 {
l = len(s)
for l > 0 && !utf8.ValidString(s[:l]) {
l--
}
}
result = append(result, s[:l])
s = s[l:]
}
return result
}
func Obj2Bytes(obj interface{}) ([]byte, error) {
// 创建一个jsonIter的Encoder
configCompatibleWithStandardLibrary := jsoniter.ConfigCompatibleWithStandardLibrary
// 将结构体转换为JSON文本并保持顺序
bytes, err := configCompatibleWithStandardLibrary.Marshal(obj)
if err != nil {
return nil, err
}
return bytes, nil
}
func GetUUID() string {
code := uuid.New().String()
code = strings.Replace(code, "-", "", -1)
return code
}
// RandomElement 返回给定切片中的随机元素
func RandomElement[T any](slice []T) (T, error) {
if len(slice) == 0 {
var zero T
return zero, fmt.Errorf("empty slice")
}
// 确保每次随机都不一样
rand.Seed(time.Now().UnixNano())
// 随机选择一个索引
index := rand.Intn(len(slice))
return slice[index], nil
}
func SliceContains(slice []string, str string) bool {
for _, item := range slice {
if strings.Contains(str, item) {
return true
}
}
return false
}
func IsImageBase64(s string) bool {
// 检查字符串是否符合数据URL的格式
if !strings.HasPrefix(s, "data:image/") || !strings.Contains(s, ";base64,") {
return false
}
if !strings.Contains(s, ";base64,") {
return false
}
// 获取";base64,"后的Base64编码部分
dataParts := strings.Split(s, ";base64,")
if len(dataParts) != 2 {
return false
}
base64Data := dataParts[1]
// 尝试Base64解码
_, err := base64.StdEncoding.DecodeString(base64Data)
return err == nil
}
func IsBase64(s string) bool {
// 检查字符串是否符合数据URL的格式
//if !strings.HasPrefix(s, "data:image/") || !strings.Contains(s, ";base64,") {
// return false
//}
if !strings.Contains(s, ";base64,") {
return false
}
// 获取";base64,"后的Base64编码部分
dataParts := strings.Split(s, ";base64,")
if len(dataParts) != 2 {
return false
}
base64Data := dataParts[1]
// 尝试Base64解码
_, err := base64.StdEncoding.DecodeString(base64Data)
return err == nil
}
//<h1 data-translate="block_headline">Sorry, you have been blocked</h1>
func IsCloudflareBlock(data string) bool {
if strings.Contains(data, `<h1 data-translate="block_headline">Sorry, you have been blocked</h1>`) {
return true
}
return false
}
func IsCloudflareChallenge(data string) bool {
// 检查基本的 HTML 结构
htmlPattern := `^<!DOCTYPE html><html.*?><head>.*?</head><body.*?>.*?</body></html>$`
// 检查 Cloudflare 特征
cfPatterns := []string{
`<title>Just a moment\.\.\.</title>`, // 标题特征
`window\._cf_chl_opt`, // CF 配置对象
`challenge-platform/h/b/orchestrate/chl_page`, // CF challenge 路径
`cdn-cgi/challenge-platform`, // CDN 路径特征
`<meta http-equiv="refresh" content="\d+">`, // 刷新 meta 标签
}
// 首先检查整体 HTML 结构
matched, _ := regexp.MatchString(htmlPattern, strings.TrimSpace(data))
if !matched {
return false
}
// 检查是否包含 Cloudflare 特征
for _, pattern := range cfPatterns {
if matched, _ := regexp.MatchString(pattern, data); matched {
return true
}
}
return false
}
func IsRateLimit(data string) bool {
if data == "Rate limit exceeded cf1" || data == "Rate limit exceeded cf2" {
return true
}
return false
}
func IsNotLogin(data string) bool {
if strings.Contains(data, `{"status":-5,"message":"not login","data":{}}`) {
return true
}
return false
}
func IsServerError(data string) bool {
if data == "Internal Server Error" {
return true
}
return false
}
func IsServerOverloaded(data string) bool {
if strings.Contains(data, `data: {"id": "", "role": "assistant", "content": "Server overloaded, please try again later.", "action": null, "recommend_actions": null, "is_prompt": false, "render_template": null, "session_state": null, "message_type": null, "type": "message_result"}`) {
return true
}
return false
}
func IsFreeLimit(data string) bool {
if strings.Contains(data, `data: {"id": "", "role": "assistant", "content": "You've reached your free usage limit today", "action": {"type": "ACTION_QUOTA_EXCEEDED", "query_string": null, "update_flow_data": null, "label": null, "user_s_input": null, "action_params": null}, "recommend_actions": null, "is_prompt": true, "render_template": null, "session_state": {"consume_usage_quota_exceeded": true}, "message_type": null, "type": "message_result"}`) {
return true
}
return false
}
func IsServiceUnavailablePage(data string) bool {
// 检查基本的 HTML 结构
htmlPattern := `^<!doctype html><html.*?><head>.*?</head><body.*?>.*?</body></html>`
// 检查 Service Unavailable 页面特征
suPatterns := []string{
`<title>Genspark</title>`, // 标题特征
`Service\s+Unavailable`, // 错误信息
`class="bb".*?class="s1".*?class="s2".*?class="s3"`, // 特征性类名结构
`genspark_logo\.png`, // Logo 图片
`gensparkpublicblob-cdn.*?\.azurefd\.net`, // CDN 域名
`<div class="tt">Service Unavailable</div>`, // 错误信息容器
}
// 首先检查整体 HTML 结构
matched, _ := regexp.MatchString(htmlPattern, strings.TrimSpace(data))
if !matched {
return false
}
// 检查特征模式,至少匹配其中的 3 个才认为是目标页面
matchCount := 0
for _, pattern := range suPatterns {
if matched, _ := regexp.MatchString(pattern, data); matched {
matchCount++
}
}
return matchCount >= 3
}
//<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"><title>Genspark</title><link rel="icon" href="https://gensparkpublicblob-cdn-e6g4btgjavb5a7gh.z03.azurefd.net/user-upload-image/manual/favicon.ico"><style>body,html{margin:0;padding:0;font-family:Arial}.bb{width:100vw;height:100vh;position:absolute;overflow:hidden}.logo img{margin:20px 0 0 24px;height:24px}.iw{display:flex;flex-direction:column;height:100vh;width:100%}.s1{position:absolute;top:0;left:0;margin-top:-5%;margin-left:15%;width:289px;height:289px;border-radius:289px;opacity:.6;background:radial-gradient(55.64% 49.84%,#2c10d6 0,rgba(44,16,214,.36) 100%);filter:blur(120px)}.s2{position:absolute;top:0;left:0;margin-top:10%;margin-left:50%;width:204.845px;height:204.845px;transform:rotate(-131.346deg);flex-shrink:0;background:radial-gradient(55.64% 49.84%,#7fd1ff 0,rgba(44,16,214,.36) 100%);filter:blur(120px)}.s3{position:absolute;bottom:0;right:0;margin-bottom:10%;margin-right:10%;width:251px;height:251px;border-radius:289.093px;background:radial-gradient(88.27% 88.27% at 90.98% 61.04%,#ce7fff 0,#ffe4af 100%);filter:blur(120px)}.cc{display:flex;justify-content:center;align-items:center;height:100%;width:100%}.hh{align-items:center;display:flex;width:100vw}.dd{margin-top:-200px}.tt{color:#000;text-align:center;font-size:40px;font-style:normal;font-weight:700}@media (max-width:800px){.tt{font-size:30px}}</style></head><body><div class="bb"><div class="s1"></div><div class="s2"></div><div class="s3"></div></div><div class="iw"><div class="hh"><div class="logo"><img src="https://gensparkpublicblob-cdn-e6g4btgjavb5a7gh.z03.azurefd.net/user-upload-image/manual/genspark_logo.png" alt="logo"></div></div><div class="cc"><div class="dd"><div class="tt">Service Unavailable</div></div></div></div></body></html>
//<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"><title>Genspark</title><link rel="icon" href="https://gensparkpublicblob-cdn-e6g4btgjavb5a7gh.z03.azurefd.net/user-upload-image/manual/favicon.ico"><style>body,html{margin:0;padding:0;font-family:Arial}.bb{width:100vw;height:100vh;position:absolute;overflow:hidden}.logo img{margin:20px 0 0 24px;height:24px}.iw{display:flex;flex-direction:column;height:100vh;width:100%!}(MISSING).s1{position:absolute;top:0;left:0;margin-top:-5%!;(MISSING)margin-left:15%!;(MISSING)width:289px;height:289px;border-radius:289px;opacity:.6;background:radial-gradient(55.64%,#2c10d6 0,rgba(44,16,214,.36) 100%!)(MISSING);filter:blur(120px)}.s2{position:absolute;top:0;left:0;margin-top:10%!;(MISSING)margin-left:50%!;(MISSING)width:204.845px;height:204.845px;transform:rotate(-131.346deg);flex-shrink:0;background:radial-gradient(55.64%,#7fd1ff 0,rgba(44,16,214,.36) 100%!)(MISSING);filter:blur(120px)}.s3{position:absolute;bottom:0;right:0;margin-bottom:10%!;(MISSING)margin-right:10%!;(MISSING)width:251px;height:251px;border-radius:289.093px;background:radial-gradient(88.27% at 90.98%,#ce7fff 0,#ffe4af 100%!)(MISSING);filter:blur(120px)}.cc{display:flex;justify-content:center;align-items:center;height:100%!;(MISSING)width:100%!}(MISSING).hh{align-items:center;display:flex;width:100vw}.dd{margin-top:-200px}.tt{color:#000;text-align:center;font-size:40px;font-style:normal;font-weight:700}@media (max-width:800px){.tt{font-size:30px}}</style></head><body><div class="bb"><div class="s1"></div><div class="s2"></div><div class="s3"></div></div><div class="iw"><div class="hh"><div class="logo"><img src="https://gensparkpublicblob-cdn-e6g4btgjavb5a7gh.z03.azurefd.net/user-upload-image/manual/genspark_logo.png" alt="logo"></div></div><div class="cc"><div class="dd"><div class="tt">Service Unavailable</div></div></div></div></body></html>
================================================
FILE: controller/api.go
================================================
package controller
import (
"github.com/deanxv/CycleTLS/cycletls"
"github.com/gin-gonic/gin"
)
// ChatForOpenAI 处理OpenAI聊天请求
func InitModelChatMap(c *gin.Context) {
client := cycletls.Init()
defer safeClose(client)
// TODO
}
================================================
FILE: controller/chat.go
================================================
package controller
import (
"bufio"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"genspark2api/common"
"genspark2api/common/config"
logger "genspark2api/common/loggger"
"genspark2api/model"
"github.com/deanxv/CycleTLS/cycletls"
"github.com/gin-gonic/gin"
"github.com/samber/lo"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
)
const (
errNoValidCookies = "No valid cookies available"
)
const (
baseURL = "https://www.genspark.ai"
apiEndpoint = baseURL + "/api/copilot/ask"
deleteEndpoint = baseURL + "/api/project/delete?project_id=%s"
uploadEndpoint = baseURL + "/api/get_upload_personal_image_url"
chatType = "COPILOT_MOA_CHAT"
imageType = "COPILOT_MOA_IMAGE"
videoType = "COPILOT_MOA_VIDEO"
responseIDFormat = "chatcmpl-%s"
)
type OpenAIChatMessage struct {
Role string `json:"role"`
Content interface{} `json:"content"`
}
type OpenAIChatCompletionRequest struct {
Messages []OpenAIChatMessage
Model string
}
// ChatForOpenAI 处理OpenAI聊天请求
func ChatForOpenAI(c *gin.Context) {
client := cycletls.Init()
defer safeClose(client)
var openAIReq model.OpenAIChatCompletionRequest
if err := c.BindJSON(&openAIReq); err != nil {
logger.Errorf(c.Request.Context(), err.Error())
c.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: "Invalid request parameters",
Type: "request_error",
Code: "500",
},
})
return
}
// 模型映射
if strings.HasPrefix(openAIReq.Model, "deepseek") {
openAIReq.Model = strings.Replace(openAIReq.Model, "deepseek", "deep-seek", 1)
}
// 初始化cookie
cookieManager := config.NewCookieManager()
cookie, err := cookieManager.GetRandomCookie()
if err != nil {
logger.Errorf(c.Request.Context(), "Failed to get initial cookie: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
return
}
if lo.Contains(common.ImageModelList, openAIReq.Model) {
responseId := fmt.Sprintf(responseIDFormat, time.Now().Format("20060102150405"))
if len(openAIReq.GetUserContent()) == 0 {
logger.Errorf(c.Request.Context(), "user content is null")
c.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: "Invalid request parameters",
Type: "request_error",
Code: "500",
},
})
return
}
jsonData, err := json.Marshal(openAIReq.GetUserContent()[0])
if err != nil {
logger.Errorf(c.Request.Context(), err.Error())
c.JSON(500, gin.H{"error": "Failed to marshal request body"})
return
}
resp, err := ImageProcess(c, client, model.OpenAIImagesGenerationRequest{
Model: openAIReq.Model,
Prompt: openAIReq.GetUserContent()[0],
})
if err != nil {
logger.Errorf(c.Request.Context(), err.Error())
c.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: err.Error(),
Type: "request_error",
Code: "500",
},
})
return
} else {
data := resp.Data
var content []string
for _, item := range data {
content = append(content, fmt.Sprintf("", item.URL))
}
if openAIReq.Stream {
streamResp := createStreamResponse(responseId, openAIReq.Model, jsonData, model.OpenAIDelta{Content: strings.Join(content, "\n"), Role: "assistant"}, nil)
err := sendSSEvent(c, streamResp)
if err != nil {
logger.Errorf(c.Request.Context(), err.Error())
c.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: err.Error(),
Type: "request_error",
Code: "500",
},
})
return
}
c.SSEvent("", " [DONE]")
return
} else {
jsonBytes, _ := json.Marshal(openAIReq.Messages)
promptTokens := common.CountTokenText(string(jsonBytes), openAIReq.Model)
completionTokens := common.CountTokenText(strings.Join(content, "\n"), openAIReq.Model)
finishReason := "stop"
// 创建并返回 OpenAIChatCompletionResponse 结构
resp := model.OpenAIChatCompletionResponse{
ID: fmt.Sprintf(responseIDFormat, time.Now().Format("20060102150405")),
Object: "chat.completion",
Created: time.Now().Unix(),
Model: openAIReq.Model,
Choices: []model.OpenAIChoice{
{
Message: model.OpenAIMessage{
Role: "assistant",
Content: strings.Join(content, "\n"),
},
FinishReason: &finishReason,
},
},
Usage: model.OpenAIUsage{
PromptTokens: promptTokens,
CompletionTokens: completionTokens,
TotalTokens: promptTokens + completionTokens,
},
}
c.JSON(200, resp)
return
}
}
}
var isSearchModel bool
if strings.HasSuffix(openAIReq.Model, "-search") {
isSearchModel = true
}
requestBody, err := createRequestBody(c, client, cookie, &openAIReq)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
//jsonData, err := json.Marshal(requestBody)
//if err != nil {
// c.JSON(500, gin.H{"error": "Failed to marshal request body"})
// return
//}
if openAIReq.Stream {
handleStreamRequest(c, client, cookie, cookieManager, requestBody, openAIReq.Model, isSearchModel)
} else {
handleNonStreamRequest(c, client, cookie, cookieManager, requestBody, openAIReq.Model, isSearchModel)
}
}
func processMessages(c *gin.Context, client cycletls.CycleTLS, cookie string, messages []model.OpenAIChatMessage) error {
//client := cycletls.Init()
//defer client.Close()
for i, message := range messages {
if contentArray, ok := message.Content.([]interface{}); ok {
for j, content := range contentArray {
if contentMap, ok := content.(map[string]interface{}); ok {
if contentType, ok := contentMap["type"].(string); ok && contentType == "image_url" {
if imageMap, ok := contentMap["image_url"].(map[string]interface{}); ok {
if url, ok := imageMap["url"].(string); ok {
err := processUrl(c, client, cookie, url, imageMap, j, contentArray)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("processUrl err %v\n", err))
return fmt.Errorf("processUrl err: %v", err)
}
}
}
}
}
}
messages[i].Content = contentArray
}
}
return nil
}
func processUrl(c *gin.Context, client cycletls.CycleTLS, cookie string, url string, imageMap map[string]interface{}, index int, contentArray []interface{}) error {
// 判断是否为URL
if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
// 下载文件
bytes, err := fetchImageBytes(url)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("fetchImageBytes err %v\n", err))
return fmt.Errorf("fetchImageBytes err %v\n", err)
}
err = processBytes(c, client, cookie, bytes, imageMap, index, contentArray)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("processBytes err %v\n", err))
return fmt.Errorf("processBytes err %v\n", err)
}
} else {
// 尝试解析base64
var bytes []byte
var err error
// 处理可能包含 data:image/ 前缀的base64
base64Str := url
if strings.Contains(url, ";base64,") {
base64Str = strings.Split(url, ";base64,")[1]
}
bytes, err = base64.StdEncoding.DecodeString(base64Str)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("base64.StdEncoding.DecodeString err %v\n", err))
return fmt.Errorf("base64.StdEncoding.DecodeString err: %v\n", err)
}
err = processBytes(c, client, cookie, bytes, imageMap, index, contentArray)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("processBytes err %v\n", err))
return fmt.Errorf("processBytes err: %v\n", err)
}
}
return nil
}
func processBytes(c *gin.Context, client cycletls.CycleTLS, cookie string, bytes []byte, imageMap map[string]interface{}, index int, contentArray []interface{}) error {
// 检查是否为图片类型
contentType := http.DetectContentType(bytes)
if strings.HasPrefix(contentType, "image/") {
// 是图片类型,转换为base64
base64Data := "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(bytes)
imageMap["url"] = base64Data
} else {
response, err := makeGetUploadUrlRequest(client, cookie)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("makeGetUploadUrlRequest err %v\n", err))
return fmt.Errorf("makeGetUploadUrlRequest err: %v\n", err)
}
var jsonResponse map[string]interface{}
if err := json.Unmarshal([]byte(response.Body), &jsonResponse); err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("Unmarshal err %v\n", err))
return fmt.Errorf("Unmarshal err: %v\n", err)
}
uploadImageUrl, ok := jsonResponse["data"].(map[string]interface{})["upload_image_url"].(string)
privateStorageUrl, ok := jsonResponse["data"].(map[string]interface{})["private_storage_url"].(string)
if !ok {
//fmt.Println("Failed to extract upload_image_url")
return fmt.Errorf("Failed to extract upload_image_url")
}
// 发送OPTIONS预检请求
//_, err = makeOptionsRequest(client, uploadImageUrl)
//if err != nil {
// return
//}
// 上传文件
_, err = makeUploadRequest(client, uploadImageUrl, bytes)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("makeUploadRequest err %v\n", err))
return fmt.Errorf("makeUploadRequest err: %v\n", err)
}
//fmt.Println(resp)
// 创建新的 private_file 格式的内容
privateFile := map[string]interface{}{
"type": "private_file",
"private_file": map[string]interface{}{
"name": "file", // 你可能需要从原始文件名或其他地方获取
"type": contentType,
"size": len(bytes),
"ext": strings.Split(contentType, "/")[1], // 简单处理,可能需要更复杂的逻辑
"private_storage_url": privateStorageUrl,
},
}
// 替换数组中的元素
contentArray[index] = privateFile
}
return nil
}
// 获取文件字节数组的函数
func fetchImageBytes(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("http.Get err: %v\n", err)
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func createRequestBody(c *gin.Context, client cycletls.CycleTLS, cookie string, openAIReq *model.OpenAIChatCompletionRequest) (map[string]interface{}, error) {
openAIReq.SystemMessagesProcess(openAIReq.Model)
if config.PRE_MESSAGES_JSON != "" {
err := openAIReq.PrependMessagesFromJSON(config.PRE_MESSAGES_JSON)
if err != nil {
return nil, fmt.Errorf("PrependMessagesFromJSON err: %v PrependMessagesFromJSON:", err, config.PRE_MESSAGES_JSON)
}
}
// 处理消息中的图像 URL
err := processMessages(c, client, cookie, openAIReq.Messages)
if err != nil {
logger.Errorf(c.Request.Context(), "processMessages err: %v", err)
return nil, fmt.Errorf("processMessages err: %v", err)
}
currentQueryString := fmt.Sprintf("type=%s", chatType)
//查找 key 对应的 value
if chatId, ok := config.ModelChatMap[openAIReq.Model]; ok {
currentQueryString = fmt.Sprintf("id=%s&type=%s", chatId, chatType)
} else if chatId, ok := config.GlobalSessionManager.GetChatID(cookie, openAIReq.Model); ok {
currentQueryString = fmt.Sprintf("id=%s&type=%s", chatId, chatType)
} else {
openAIReq.FilterUserMessage()
}
requestWebKnowledge := false
models := []string{openAIReq.Model}
if strings.HasSuffix(openAIReq.Model, "-search") {
openAIReq.Model = strings.Replace(openAIReq.Model, "-search", "", 1)
requestWebKnowledge = true
models = []string{openAIReq.Model}
}
if !lo.Contains(common.TextModelList, openAIReq.Model) {
models = common.MixtureModelList
}
// 创建请求体
requestBody := map[string]interface{}{
"type": chatType,
"current_query_string": currentQueryString,
"messages": openAIReq.Messages,
"action_params": map[string]interface{}{},
"extra_data": map[string]interface{}{
"models": models,
"run_with_another_model": false,
"writingContent": nil,
"request_web_knowledge": requestWebKnowledge,
},
}
logger.Debug(c.Request.Context(), fmt.Sprintf("RequestBody: %v", requestBody))
return requestBody, nil
}
func createImageRequestBody(c *gin.Context, cookie string, openAIReq *model.OpenAIImagesGenerationRequest, chatId string) (map[string]interface{}, error) {
if openAIReq.Model == "dall-e-3" {
openAIReq.Model = "dalle-3"
}
// 创建模型配置
modelConfigs := []map[string]interface{}{
{
"model": openAIReq.Model,
"aspect_ratio": "auto",
"use_personalized_models": false,
"fashion_profile_id": nil,
"hd": false,
"reflection_enabled": false,
"style": "auto",
},
}
// 创建消息数组
var messages []map[string]interface{}
if openAIReq.Image != "" {
var base64Data string
if strings.HasPrefix(openAIReq.Image, "http://") || strings.HasPrefix(openAIReq.Image, "https://") {
// 下载文件
bytes, err := fetchImageBytes(openAIReq.Image)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("fetchImageBytes err %v\n", err))
return nil, fmt.Errorf("fetchImageBytes err %v\n", err)
}
contentType := http.DetectContentType(bytes)
if strings.HasPrefix(contentType, "image/") {
// 是图片类型,转换为base64
base64Data = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(bytes)
}
} else if common.IsImageBase64(openAIReq.Image) {
// 如果已经是 base64 格式
if !strings.HasPrefix(openAIReq.Image, "data:image") {
base64Data = "data:image/jpeg;base64," + openAIReq.Image
} else {
base64Data = openAIReq.Image
}
}
// 构建包含图片的消息
if base64Data != "" {
messages = []map[string]interface{}{
{
"role": "user",
"content": []map[string]interface{}{
{
"type": "image_url",
"image_url": map[string]interface{}{
"url": base64Data,
},
},
{
"type": "text",
"text": openAIReq.Prompt,
},
},
},
}
}
}
// 如果没有图片或处理图片失败,使用纯文本消息
if len(messages) == 0 {
messages = []map[string]interface{}{
{
"role": "user",
"content": openAIReq.Prompt,
},
}
}
var currentQueryString string
if len(chatId) != 0 {
currentQueryString = fmt.Sprintf("id=%s&type=%s", chatId, imageType)
} else {
currentQueryString = fmt.Sprintf("type=%s", imageType)
}
// 创建请求体
requestBody := map[string]interface{}{
"type": "COPILOT_MOA_IMAGE",
//"current_query_string": "type=COPILOT_MOA_IMAGE",
"current_query_string": currentQueryString,
"messages": messages,
"user_s_input": openAIReq.Prompt,
"action_params": map[string]interface{}{},
"extra_data": map[string]interface{}{
"model_configs": modelConfigs,
"llm_model": "gpt-4o",
"imageModelMap": map[string]interface{}{},
"writingContent": nil,
},
}
logger.Debug(c.Request.Context(), fmt.Sprintf("RequestBody: %v", requestBody))
if strings.TrimSpace(config.RecaptchaProxyUrl) == "" ||
(!strings.HasPrefix(config.RecaptchaProxyUrl, "http://") &&
!strings.HasPrefix(config.RecaptchaProxyUrl, "https://")) {
return requestBody, nil
} else {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
// 检查并补充 RecaptchaProxyUrl 的末尾斜杠
if !strings.HasSuffix(config.RecaptchaProxyUrl, "/") {
config.RecaptchaProxyUrl += "/"
}
// 创建请求
req, err := http.NewRequest("GET", fmt.Sprintf("%sgenspark", config.RecaptchaProxyUrl), nil)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("创建/genspark请求失败 %v\n", err))
return nil, err
}
// 设置请求头
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Cookie", cookie)
// 发送请求
resp, err := client.Do(req)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("发送/genspark请求失败 %v\n", err))
return nil, err
}
defer resp.Body.Close()
// 读取响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark响应失败 %v\n", err))
return nil, err
}
type Response struct {
Code int `json:"code"`
Token string `json:"token"`
Message string `json:"message"`
}
if resp.StatusCode == 200 {
var response Response
if err := json.Unmarshal(body, &response); err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark JSON 失败 %v\n", err))
return nil, err
}
if response.Code == 200 {
logger.Debugf(c.Request.Context(), fmt.Sprintf("g_recaptcha_token: %v\n", response.Token))
requestBody["g_recaptcha_token"] = response.Token
logger.Infof(c.Request.Context(), fmt.Sprintf("cheat success!"))
return requestBody, nil
} else {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark token 失败 %v\n", err))
return nil, err
}
} else {
logger.Errorf(c.Request.Context(), fmt.Sprintf("请求/genspark失败 %v\n", err))
return nil, err
}
}
}
// createStreamResponse 创建流式响应
func createStreamResponse(responseId, modelName string, jsonData []byte, delta model.OpenAIDelta, finishReason *string) model.OpenAIChatCompletionResponse {
promptTokens := common.CountTokenText(string(jsonData), modelName)
completionTokens := common.CountTokenText(delta.Content, modelName)
return model.OpenAIChatCompletionResponse{
ID: responseId,
Object: "chat.completion.chunk",
Created: time.Now().Unix(),
Model: modelName,
Choices: []model.OpenAIChoice{
{
Index: 0,
Delta: delta,
FinishReason: finishReason,
},
},
Usage: model.OpenAIUsage{
PromptTokens: promptTokens,
CompletionTokens: completionTokens,
TotalTokens: promptTokens + completionTokens,
},
}
}
// handleMessageFieldDelta 处理消息字段增量
func handleMessageFieldDelta(c *gin.Context, event map[string]interface{}, responseId, modelName string, jsonData []byte) error {
fieldName, ok := event["field_name"].(string)
if !ok {
return nil
}
// 基础允许列表(所有配置下都需要处理的字段)
baseAllowed := fieldName == "session_state.answer" ||
strings.Contains(fieldName, "session_state.streaming_detail_answer") ||
fieldName == "session_state.streaming_markmap"
// 需要显示思考过程时需要额外处理的字段
if config.ReasoningHide != 1 {
baseAllowed = baseAllowed ||
fieldName == "session_state.answerthink_is_started" ||
fieldName == "session_state.answerthink" ||
fieldName == "session_state.answerthink_is_finished"
}
if !baseAllowed {
return nil
}
// 获取 delta 内容
var delta string
switch {
case (modelName == "o1" || modelName == "o3-mini-high") && fieldName == "session_state.answer":
delta, _ = event["field_value"].(string)
default:
delta, _ = event["delta"].(string)
}
// 创建基础响应
createResponse := func(content string) model.OpenAIChatCompletionResponse {
return createStreamResponse(
responseId,
modelName,
jsonData,
model.OpenAIDelta{Content: content, Role: "assistant"},
nil,
)
}
// 发送基础事件
var err error
if err = sendSSEvent(c, createResponse(delta)); err != nil {
return err
}
// 处理思考过程标记
if config.ReasoningHide != 1 {
switch fieldName {
case "session_state.answerthink_is_started":
err = sendSSEvent(c, createResponse("<think>\n"))
case "session_state.answerthink_is_finished":
err = sendSSEvent(c, createResponse("\n</think>"))
}
}
return err
}
type Content struct {
DetailAnswer string `json:"detailAnswer"`
}
func getDetailAnswer(eventMap map[string]interface{}) (string, error) {
// 获取 content 字段的值
contentStr, ok := eventMap["content"].(string)
if !ok {
return "", fmt.Errorf("content is not a string")
}
// 解析内层的 JSON
var content Content
if err := json.Unmarshal([]byte(contentStr), &content); err != nil {
return "", err
}
return content.DetailAnswer, nil
}
// handleMessageResult 处理消息结果
func handleMessageResult(c *gin.Context, event map[string]interface{}, responseId, modelName string, jsonData []byte, searchModel bool) bool {
finishReason := "stop"
var delta string
var err error
if modelName == "o1" && searchModel {
delta, err = getDetailAnswer(event)
if err != nil {
logger.Errorf(c.Request.Context(), "getDetailAnswer err: %v", err)
return false
}
}
streamResp := createStreamResponse(responseId, modelName, jsonData, model.OpenAIDelta{Content: delta, Role: "assistant"}, &finishReason)
if err := sendSSEvent(c, streamResp); err != nil {
logger.Warnf(c.Request.Context(), "sendSSEvent err: %v", err)
return false
}
c.SSEvent("", " [DONE]")
return false
}
// sendSSEvent 发送SSE事件
func sendSSEvent(c *gin.Context, response model.OpenAIChatCompletionResponse) error {
jsonResp, err := json.Marshal(response)
if err != nil {
logger.Errorf(c.Request.Context(), "Failed to marshal response: %v", err)
return err
}
c.SSEvent("", " "+string(jsonResp))
c.Writer.Flush()
return nil
}
// makeRequest 发送HTTP请求
func makeRequest(client cycletls.CycleTLS, jsonData []byte, cookie string, isStream bool) (cycletls.Response, error) {
accept := "application/json"
if isStream {
accept = "text/event-stream"
}
return client.Do(apiEndpoint, cycletls.Options{
Timeout: 10 * 60 * 60,
Proxy: config.ProxyUrl, // 在每个请求中设置代理
Body: string(jsonData),
Method: "POST",
Headers: map[string]string{
"Content-Type": "application/json",
"Accept": accept,
"Origin": baseURL,
"Referer": baseURL + "/",
"Cookie": cookie,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
},
}, "POST")
}
// makeRequest 发送HTTP请求
func makeImageRequest(client cycletls.CycleTLS, jsonData []byte, cookie string) (cycletls.Response, error) {
accept := "*/*"
return client.Do(apiEndpoint, cycletls.Options{
UserAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
Timeout: 10 * 60 * 60,
Proxy: config.ProxyUrl, // 在每个请求中设置代理
Body: string(jsonData),
Method: "POST",
Headers: map[string]string{
"Content-Type": "application/json",
"Accept": accept,
"Origin": baseURL,
"Referer": baseURL + "/",
"Cookie": cookie,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
},
}, "POST")
}
func makeDeleteRequest(client cycletls.CycleTLS, cookie, projectId string) (cycletls.Response, error) {
// 不删除环境变量中的map中的对话
for _, v := range config.ModelChatMap {
if v == projectId {
return cycletls.Response{}, nil
}
}
for _, v := range config.GlobalSessionManager.GetChatIDsByCookie(cookie) {
if v == projectId {
return cycletls.Response{}, nil
}
}
for _, v := range config.SessionImageChatMap {
if v == projectId {
return cycletls.Response{}, nil
}
}
accept := "application/json"
return client.Do(fmt.Sprintf(deleteEndpoint, projectId), cycletls.Options{
Timeout: 10 * 60 * 60,
Proxy: config.ProxyUrl, // 在每个请求中设置代理
Method: "GET",
Headers: map[string]string{
"Content-Type": "application/json",
"Accept": accept,
"Origin": baseURL,
"Referer": baseURL + "/",
"Cookie": cookie,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
},
}, "GET")
}
func makeGetUploadUrlRequest(client cycletls.CycleTLS, cookie string) (cycletls.Response, error) {
accept := "*/*"
return client.Do(fmt.Sprintf(uploadEndpoint), cycletls.Options{
Timeout: 10 * 60 * 60,
Proxy: config.ProxyUrl, // 在每个请求中设置代理
Method: "GET",
Headers: map[string]string{
"Content-Type": "application/json",
"Accept": accept,
"Origin": baseURL,
"Referer": baseURL + "/",
"Cookie": cookie,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
},
}, "GET")
}
//func makeOptionsRequest(client cycletls.CycleTLS, uploadUrl string) (cycletls.Response, error) {
// return client.Do(uploadUrl, cycletls.Options{
// Method: "OPTIONS",
// Headers: map[string]string{
// "Accept": "*/*",
// "Access-Control-Request-Headers": "x-ms-blob-type",
// "Access-Control-Request-Method": "PUT",
// "Origin": "https://www.genspark.ai",
// "Sec-Fetch-Dest": "empty",
// "Sec-Fetch-Mode": "cors",
// "Sec-Fetch-Site": "cross-site",
// },
// UserAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
// }, "OPTIONS")
//}
func makeUploadRequest(client cycletls.CycleTLS, uploadUrl string, fileBytes []byte) (cycletls.Response, error) {
return client.Do(uploadUrl, cycletls.Options{
Timeout: 10 * 60 * 60,
Proxy: config.ProxyUrl, // 在每个请求中设置代理
Method: "PUT",
Body: string(fileBytes),
Headers: map[string]string{
"Accept": "*/*",
"x-ms-blob-type": "BlockBlob",
"Content-Type": "application/octet-stream",
"Content-Length": fmt.Sprintf("%d", len(fileBytes)),
"Origin": "https://www.genspark.ai",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "cross-site",
},
}, "PUT")
}
// handleStreamRequest 处理流式请求
//func handleStreamRequest(c *gin.Context, client cycletls.CycleTLS, cookie string, jsonData []byte, model string) {
// c.Header("Content-Type", "text/event-stream")
// c.Header("Cache-Control", "no-cache")
// c.Header("Connection", "keep-alive")
//
// responseId := fmt.Sprintf(responseIDFormat, time.Now().Format("20060102150405"))
//
// c.Stream(func(w io.Writer) bool {
// sseChan, err := makeStreamRequest(c, client, jsonData, cookie)
// if err != nil {
// logger.Errorf(c.Request.Context(), "makeStreamRequest err: %v", err)
// return false
// }
//
// return handleStreamResponse(c, sseChan, responseId, cookie, model, jsonData)
// })
//}
func handleStreamRequest(c *gin.Context, client cycletls.CycleTLS, cookie string, cookieManager *config.CookieManager, requestBody map[string]interface{}, modelName string, searchModel bool) {
const (
errNoValidCookies = "No valid cookies available"
errCloudflareChallengeMsg = "Detected Cloudflare Challenge Page"
errCloudflareBlock = "CloudFlare: Sorry, you have been blocked"
errServerErrMsg = "An error occurred with the current request, please try again."
errServiceUnavailable = "Genspark Service Unavailable"
)
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
responseId := fmt.Sprintf(responseIDFormat, time.Now().Format("20060102150405"))
ctx := c.Request.Context()
maxRetries := len(cookieManager.Cookies)
c.Stream(func(w io.Writer) bool {
for attempt := 0; attempt < maxRetries; attempt++ {
requestBody, err := cheat(requestBody, c, cookie)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return false
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
c.JSON(500, gin.H{"error": "Failed to marshal request body"})
return false
}
sseChan, err := makeStreamRequest(c, client, jsonData, cookie)
if err != nil {
logger.Errorf(ctx, "makeStreamRequest err on attempt %d: %v", attempt+1, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return false
}
var projectId string
isRateLimit := false
SSELoop:
for response := range sseChan {
if response.Done {
logger.Debugf(ctx, response.Data)
return false
}
data := response.Data
if data == "" {
continue
}
logger.Debug(ctx, strings.TrimSpace(data))
switch {
case common.IsCloudflareChallenge(data):
logger.Errorf(ctx, errCloudflareChallengeMsg)
c.JSON(http.StatusInternalServerError, gin.H{"error": errCloudflareChallengeMsg})
return false
case common.IsCloudflareBlock(data):
logger.Errorf(ctx, errCloudflareBlock)
c.JSON(http.StatusInternalServerError, gin.H{"error": errCloudflareBlock})
return false
case common.IsServiceUnavailablePage(data):
logger.Errorf(ctx, errServiceUnavailable)
c.JSON(http.StatusInternalServerError, gin.H{"error": errServiceUnavailable})
return false
case common.IsServerError(data):
logger.Errorf(ctx, errServerErrMsg)
c.JSON(http.StatusInternalServerError, gin.H{"error": errServerErrMsg})
return false
case common.IsRateLimit(data):
isRateLimit = true
logger.Warnf(ctx, "Cookie rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
config.AddRateLimitCookie(cookie, time.Now().Add(time.Duration(config.RateLimitCookieLockDuration)*time.Second))
break SSELoop // 使用 label 跳出 SSE 循环
case common.IsFreeLimit(data):
isRateLimit = true
logger.Warnf(ctx, "Cookie free rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
config.AddRateLimitCookie(cookie, time.Now().Add(24*60*60*time.Second))
// 删除cookie
//config.RemoveCookie(cookie)
break SSELoop // 使用 label 跳出 SSE 循环
case common.IsNotLogin(data):
isRateLimit = true
logger.Warnf(ctx, "Cookie Not Login, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
// 删除cookie
config.RemoveCookie(cookie)
break SSELoop // 使用 label 跳出 SSE 循环
}
// 处理事件流数据
if shouldContinue := processStreamData(c, data, &projectId, cookie, responseId, modelName, jsonData, searchModel); !shouldContinue {
return false
}
}
if !isRateLimit {
return true
}
// 获取下一个可用的cookie继续尝试
cookie, err = cookieManager.GetNextCookie()
if err != nil {
logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
return false
}
// requestBody重制chatId
currentQueryString := fmt.Sprintf("type=%s", chatType)
if chatId, ok := config.GlobalSessionManager.GetChatID(cookie, modelName); ok {
currentQueryString = fmt.Sprintf("id=%s&type=%s", chatId, chatType)
}
requestBody["current_query_string"] = currentQueryString
}
logger.Errorf(ctx, "All cookies exhausted after %d attempts", maxRetries)
c.JSON(http.StatusInternalServerError, gin.H{"error": "All cookies are temporarily unavailable."})
return false
})
}
func cheat(requestBody map[string]interface{}, c *gin.Context, cookie string) (map[string]interface{}, error) {
if strings.TrimSpace(config.RecaptchaProxyUrl) == "" ||
(!strings.HasPrefix(config.RecaptchaProxyUrl, "http://") &&
!strings.HasPrefix(config.RecaptchaProxyUrl, "https://")) {
return requestBody, nil
} else {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
// 检查并补充 RecaptchaProxyUrl 的末尾斜杠
if !strings.HasSuffix(config.RecaptchaProxyUrl, "/") {
config.RecaptchaProxyUrl += "/"
}
// 创建请求
req, err := http.NewRequest("GET", fmt.Sprintf("%sgenspark", config.RecaptchaProxyUrl), nil)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("创建/genspark请求失败 %v\n", err))
return nil, err
}
// 设置请求头
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Cookie", cookie)
// 发送请求
resp, err := client.Do(req)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("发送/genspark请求失败 %v\n", err))
return nil, err
}
defer resp.Body.Close()
// 读取响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark响应失败 %v\n", err))
return nil, err
}
type Response struct {
Code int `json:"code"`
Token string `json:"token"`
Message string `json:"message"`
}
if resp.StatusCode == 200 {
var response Response
if err := json.Unmarshal(body, &response); err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark JSON 失败 %v\n", err))
return nil, err
}
if response.Code == 200 {
logger.Debugf(c.Request.Context(), fmt.Sprintf("g_recaptcha_token: %v\n", response.Token))
requestBody["g_recaptcha_token"] = response.Token
logger.Infof(c.Request.Context(), fmt.Sprintf("cheat success!"))
return requestBody, nil
} else {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark token 失败,查看 playwright-proxy log"))
return nil, err
}
} else {
logger.Errorf(c.Request.Context(), fmt.Sprintf("请求/genspark失败,查看 playwright-proxy log"))
return nil, err
}
}
}
// 处理流式数据的辅助函数,返回bool表示是否继续处理
func processStreamData(c *gin.Context, data string, projectId *string, cookie, responseId, model string, jsonData []byte, searchModel bool) bool {
data = strings.TrimSpace(data)
//if !strings.HasPrefix(data, "data: ") {
// return true
//}
data = strings.TrimPrefix(data, "data: ")
if !strings.HasPrefix(data, "{\"id\":") && !strings.HasPrefix(data, "{\"message_id\":") {
return true
}
var event map[string]interface{}
if err := json.Unmarshal([]byte(data), &event); err != nil {
logger.Errorf(c.Request.Context(), "Failed to unmarshal event: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return false
}
eventType, ok := event["type"].(string)
if !ok {
return true
}
switch eventType {
case "project_start":
*projectId, _ = event["id"].(string)
case "message_field":
if err := handleMessageFieldDelta(c, event, responseId, model, jsonData); err != nil {
logger.Errorf(c.Request.Context(), "handleMessageFieldDelta err: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return false
}
case "message_field_delta":
if err := handleMessageFieldDelta(c, event, responseId, model, jsonData); err != nil {
logger.Errorf(c.Request.Context(), "handleMessageFieldDelta err: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return false
}
case "message_result":
go func() {
if config.AutoModelChatMapType == 1 {
// 保存映射
config.GlobalSessionManager.AddSession(cookie, model, *projectId)
} else {
if config.AutoDelChat == 1 {
client := cycletls.Init()
defer safeClose(client)
makeDeleteRequest(client, cookie, *projectId)
}
}
}()
return handleMessageResult(c, event, responseId, model, jsonData, searchModel)
}
return true
}
func makeStreamRequest(c *gin.Context, client cycletls.CycleTLS, jsonData []byte, cookie string) (<-chan cycletls.SSEResponse, error) {
options := cycletls.Options{
Timeout: 10 * 60 * 60,
Proxy: config.ProxyUrl, // 在每个请求中设置代理
Body: string(jsonData),
Method: "POST",
Headers: map[string]string{
"Content-Type": "application/json",
"Accept": "text/event-stream",
"Origin": baseURL,
"Referer": baseURL + "/",
"Cookie": cookie,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
},
}
logger.Debug(c.Request.Context(), fmt.Sprintf("cookie: %v", cookie))
sseChan, err := client.DoSSE(apiEndpoint, options, "POST")
if err != nil {
logger.Errorf(c, "Failed to make stream request: %v", err)
return nil, fmt.Errorf("Failed to make stream request: %v", err)
}
return sseChan, nil
}
// handleNonStreamRequest 处理非流式请求
//
// func handleNonStreamRequest(c *gin.Context, client cycletls.CycleTLS, cookie string, jsonData []byte, modelName string) {
// response, err := makeRequest(client, jsonData, cookie, false)
// if err != nil {
// logger.Errorf(c.Request.Context(), "makeRequest err: %v", err)
// c.JSON(500, gin.H{"error": err.Error()})
// return
// }
//
// reader := strings.NewReader(response.Body)
// scanner := bufio.NewScanner(reader)
//
// var content string
// var firstline string
// for scanner.Scan() {
// line := scanner.Text()
// firstline = line
// logger.Debug(c.Request.Context(), strings.TrimSpace(line))
//
// if common.IsCloudflareChallenge(line) {
// logger.Errorf(c.Request.Context(), "Detected Cloudflare Challenge Page")
// c.JSON(500, gin.H{"error": "Detected Cloudflare Challenge Page"})
// return
// }
//
// if common.IsRateLimit(line) {
// logger.Errorf(c.Request.Context(), "Cookie has reached the rate Limit")
// c.JSON(500, gin.H{"error": "Cookie has reached the rate Limit"})
// return
// }
//
// if strings.HasPrefix(line, "data: ") {
// data := strings.TrimPrefix(line, "data: ")
// var parsedResponse struct {
// Type string `json:"type"`
// FieldName string `json:"field_name"`
// Content string `json:"content"`
// }
// if err := json.Unmarshal([]byte(data), &parsedResponse); err != nil {
// logger.Warnf(c.Request.Context(), "Failed to unmarshal response: %v", err)
// continue
// }
// if parsedResponse.Type == "message_result" {
// content = parsedResponse.Content
// break
// }
// }
// }
//
// if content == "" {
// logger.Errorf(c.Request.Context(), firstline)
// c.JSON(500, gin.H{"error": "No valid response content"})
// return
// }
//
// promptTokens := common.CountTokenText(string(jsonData), modelName)
// completionTokens := common.CountTokenText(content, modelName)
//
// finishReason := "stop"
// // 创建并返回 OpenAIChatCompletionResponse 结构
// resp := model.OpenAIChatCompletionResponse{
// ID: fmt.Sprintf(responseIDFormat, time.Now().Format("20060102150405")),
// Object: "chat.completion",
// Created: time.Now().Unix(),
// Model: modelName,
// Choices: []model.OpenAIChoice{
// {
// Message: model.OpenAIMessage{
// Role: "assistant",
// Content: content,
// },
// FinishReason: &finishReason,
// },
// },
// Usage: model.OpenAIUsage{
// PromptTokens: promptTokens,
// CompletionTokens: completionTokens,
// TotalTokens: promptTokens + completionTokens,
// },
// }
//
// c.JSON(200, resp)
// }
func handleNonStreamRequest(c *gin.Context, client cycletls.CycleTLS, cookie string, cookieManager *config.CookieManager, requestBody map[string]interface{}, modelName string, searchModel bool) {
const (
errCloudflareChallengeMsg = "Detected Cloudflare Challenge Page"
errCloudflareBlock = "CloudFlare: Sorry, you have been blocked"
errServerErrMsg = "An error occurred with the current request, please try again."
errServiceUnavailable = "Genspark Service Unavailable"
errNoValidResponseContent = "No valid response content"
)
ctx := c.Request.Context()
maxRetries := len(cookieManager.Cookies)
for attempt := 0; attempt < maxRetries; attempt++ {
requestBody, err := cheat(requestBody, c, cookie)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
c.JSON(500, gin.H{"error": "Failed to marshal request body"})
return
}
response, err := makeRequest(client, jsonData, cookie, false)
if err != nil {
logger.Errorf(ctx, "makeRequest err: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
scanner := bufio.NewScanner(strings.NewReader(response.Body))
var content string
var answerThink string
var firstLine string
var projectId string
isRateLimit := false
for scanner.Scan() {
line := scanner.Text()
if firstLine == "" {
firstLine = line
}
if line == "" {
continue
}
logger.Debug(ctx, strings.TrimSpace(line))
switch {
case common.IsCloudflareChallenge(line):
logger.Errorf(ctx, errCloudflareChallengeMsg)
c.JSON(http.StatusInternalServerError, gin.H{"error": errCloudflareChallengeMsg})
return
case common.IsCloudflareBlock(line):
logger.Errorf(ctx, errCloudflareBlock)
c.JSON(http.StatusInternalServerError, gin.H{"error": errCloudflareBlock})
return
case common.IsRateLimit(line):
isRateLimit = true
logger.Warnf(ctx, "Cookie rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
config.AddRateLimitCookie(cookie, time.Now().Add(time.Duration(config.RateLimitCookieLockDuration)*time.Second))
break
case common.IsFreeLimit(line):
isRateLimit = true
logger.Warnf(ctx, "Cookie free rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
config.AddRateLimitCookie(cookie, time.Now().Add(24*60*60*time.Second))
// 删除cookie
//config.RemoveCookie(cookie)
break
case common.IsNotLogin(line):
isRateLimit = true
logger.Warnf(ctx, "Cookie Not Login, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
// 删除cookie
config.RemoveCookie(cookie)
break
case common.IsServiceUnavailablePage(line):
logger.Errorf(ctx, errServiceUnavailable)
c.JSON(http.StatusInternalServerError, gin.H{"error": errServiceUnavailable})
return
case common.IsServerError(line):
logger.Errorf(ctx, errServerErrMsg)
c.JSON(http.StatusInternalServerError, gin.H{"error": errServerErrMsg})
return
case strings.HasPrefix(line, "data: "):
data := strings.TrimPrefix(line, "data: ")
var parsedResponse struct {
Type string `json:"type"`
FieldName string `json:"field_name"`
Content string `json:"content"`
Id string `json:"id"`
Delta string `json:"delta"`
}
if err := json.Unmarshal([]byte(data), &parsedResponse); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if parsedResponse.Type == "project_start" {
projectId = parsedResponse.Id
}
if parsedResponse.Type == "message_field" {
// 提取思考过程
if config.ReasoningHide != 1 {
if parsedResponse.FieldName == "session_state.answerthink_is_started" {
answerThink = "<think>\n"
}
if parsedResponse.FieldName == "session_state.answerthink_is_finished" {
answerThink = answerThink + "\n</think>"
}
}
}
if parsedResponse.Type == "message_field_delta" {
// 提取思考过程
if config.ReasoningHide != 1 {
if parsedResponse.FieldName == "session_state.answerthink" {
answerThink = answerThink + parsedResponse.Delta
}
}
}
if parsedResponse.Type == "message_result" {
// 删除临时会话
go func() {
if config.AutoModelChatMapType == 1 {
// 保存映射
config.GlobalSessionManager.AddSession(cookie, modelName, projectId)
} else {
if config.AutoDelChat == 1 {
client := cycletls.Init()
defer safeClose(client)
makeDeleteRequest(client, cookie, projectId)
}
}
}()
if modelName == "o1" && searchModel {
// 解析内层的 JSON
var content Content
if err := json.Unmarshal([]byte(parsedResponse.Content), &content); err != nil {
logger.Errorf(ctx, "Failed to unmarshal response content: %v err %s", parsedResponse.Content, err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to unmarshal response content"})
return
}
parsedResponse.Content = content.DetailAnswer
}
content = strings.TrimSpace(answerThink + parsedResponse.Content)
break
}
}
}
if !isRateLimit {
if content == "" {
logger.Warnf(ctx, firstLine)
//c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidResponseContent})
} else {
promptTokens := common.CountTokenText(string(jsonData), modelName)
completionTokens := common.CountTokenText(content, modelName)
finishReason := "stop"
c.JSON(http.StatusOK, model.OpenAIChatCompletionResponse{
ID: fmt.Sprintf(responseIDFormat, time.Now().Format("20060102150405")),
Object: "chat.completion",
Created: time.Now().Unix(),
Model: modelName,
Choices: []model.OpenAIChoice{{
Message: model.OpenAIMessage{
Role: "assistant",
Content: content,
},
FinishReason: &finishReason,
}},
Usage: model.OpenAIUsage{
PromptTokens: promptTokens,
CompletionTokens: completionTokens,
TotalTokens: promptTokens + completionTokens,
},
})
return
}
}
cookie, err = cookieManager.GetNextCookie()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "No more valid cookies available"})
return
}
// requestBody重制chatId
currentQueryString := fmt.Sprintf("type=%s", chatType)
if chatId, ok := config.GlobalSessionManager.GetChatID(cookie, modelName); ok {
currentQueryString = fmt.Sprintf("id=%s&type=%s", chatId, chatType)
}
requestBody["current_query_string"] = currentQueryString
}
logger.Errorf(ctx, "All cookies exhausted after %d attempts", maxRetries)
c.JSON(http.StatusInternalServerError, gin.H{"error": "All cookies are temporarily unavailable."})
}
func OpenaiModels(c *gin.Context) {
var modelsResp []string
modelsResp = common.DefaultOpenaiModelList
var openaiModelListResponse model.OpenaiModelListResponse
var openaiModelResponse []model.OpenaiModelResponse
openaiModelListResponse.Object = "list"
for _, modelResp := range modelsResp {
openaiModelResponse = append(openaiModelResponse, model.OpenaiModelResponse{
ID: modelResp,
Object: "model",
})
}
openaiModelListResponse.Data = openaiModelResponse
c.JSON(http.StatusOK, openaiModelListResponse)
return
}
func ImagesForOpenAI(c *gin.Context) {
client := cycletls.Init()
defer safeClose(client)
var openAIReq model.OpenAIImagesGenerationRequest
if err := c.BindJSON(&openAIReq); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
// 初始化cookie
//cookieManager := config.NewCookieManager()
//cookie, err := cookieManager.GetRandomCookie()
//
//if err != nil {
// logger.Errorf(c.Request.Context(), "Failed to get initial cookie: %v", err)
// c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
// return
//}
resp, err := ImageProcess(c, client, openAIReq)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("ImageProcess err %v\n", err))
c.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: err.Error(),
Type: "request_error",
Code: "500",
},
})
return
} else {
c.JSON(200, resp)
}
}
func ImageProcess(c *gin.Context, client cycletls.CycleTLS, openAIReq model.OpenAIImagesGenerationRequest) (*model.OpenAIImagesGenerationResponse, error) {
const (
errNoValidCookies = "No valid cookies available"
errRateLimitMsg = "Rate limit reached, please try again later"
errServerErrMsg = "An error occurred with the current request, please try again"
errNoValidTaskIDs = "No valid task IDs received"
)
var (
sessionImageChatManager *config.SessionMapManager
maxRetries int
cookie string
chatId string
)
cookieManager := config.NewCookieManager()
sessionImageChatManager = config.NewSessionMapManager()
ctx := c.Request.Context()
// Initialize session manager and get initial cookie
if len(config.SessionImageChatMap) == 0 {
//logger.Warnf(ctx, "未配置环境变量 SESSION_IMAGE_CHAT_MAP, 可能会生图失败!")
maxRetries = len(cookieManager.Cookies)
var err error
cookie, err = cookieManager.GetRandomCookie()
if err != nil {
logger.Errorf(ctx, "Failed to get initial cookie: %v", err)
return nil, fmt.Errorf(errNoValidCookies)
}
} else {
maxRetries = sessionImageChatManager.GetSize()
cookie, chatId, _ = sessionImageChatManager.GetRandomKeyValue()
}
for attempt := 0; attempt < maxRetries; attempt++ {
// Create request body
requestBody, err := createImageRequestBody(c, cookie, &openAIReq, chatId)
if err != nil {
logger.Errorf(ctx, "Failed to create request body: %v", err)
return nil, err
}
// Marshal request body
jsonData, err := json.Marshal(requestBody)
if err != nil {
logger.Errorf(ctx, "Failed to marshal request body: %v", err)
return nil, err
}
// Make request
response, err := makeImageRequest(client, jsonData, cookie)
if err != nil {
logger.Errorf(ctx, "Failed to make image request: %v", err)
return nil, err
}
body := response.Body
// Handle different response cases
switch {
case common.IsRateLimit(body):
logger.Warnf(ctx, "Cookie rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
//if sessionImageChatManager != nil {
// cookie, chatId, err = sessionImageChatManager.GetNextKeyValue()
// if err != nil {
// logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
// c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
// return nil, fmt.Errorf(errNoValidCookies)
// }
//} else {
//cookieManager := config.NewCookieManager()
config.AddRateLimitCookie(cookie, time.Now().Add(time.Duration(config.RateLimitCookieLockDuration)*time.Second))
cookie, err = cookieManager.GetNextCookie()
if err != nil {
logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
return nil, fmt.Errorf(errNoValidCookies)
//}
}
continue
case common.IsFreeLimit(body):
logger.Warnf(ctx, "Cookie free rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
//if sessionImageChatManager != nil {
// cookie, chatId, err = sessionImageChatManager.GetNextKeyValue()
// if err != nil {
// logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
// c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
// return nil, fmt.Errorf(errNoValidCookies)
// }
//} else {
//cookieManager := config.NewCookieManager()
config.AddRateLimitCookie(cookie, time.Now().Add(24*60*60*time.Second))
// 删除cookie
//config.RemoveCookie(cookie)
cookie, err = cookieManager.GetNextCookie()
if err != nil {
logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
return nil, fmt.Errorf(errNoValidCookies)
//}
}
continue
case common.IsNotLogin(body):
logger.Warnf(ctx, "Cookie Not Login, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
//if sessionImageChatManager != nil {
// //sessionImageChatManager.RemoveKey(cookie)
// cookie, chatId, err = sessionImageChatManager.GetNextKeyValue()
// if err != nil {
// logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
// c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
// return nil, fmt.Errorf(errNoValidCookies)
// }
//} else {
//cookieManager := config.NewCookieManager()
//err := cookieManager.RemoveCookie(cookie)
//if err != nil {
// logger.Errorf(ctx, "Failed to remove cookie: %v", err)
//}
cookie, err = cookieManager.GetNextCookie()
if err != nil {
logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
return nil, fmt.Errorf(errNoValidCookies)
//}
}
continue
case common.IsServerError(body):
logger.Errorf(ctx, errServerErrMsg)
return nil, fmt.Errorf(errServerErrMsg)
case common.IsServerOverloaded(body):
//logger.Errorf(ctx, fmt.Sprintf("Server overloaded, please try again later.%s", "官方服务超载或环境变量 SESSION_IMAGE_CHAT_MAP 未配置"))
logger.Errorf(ctx, fmt.Sprintf("Server overloaded, please try again later.%s", "官方服务超载"))
return nil, fmt.Errorf("Server overloaded, please try again later.")
}
// Extract task IDs
projectId, taskIDs := extractTaskIDs(response.Body)
if len(taskIDs) == 0 {
logger.Errorf(ctx, "Response body: %s", response.Body)
return nil, fmt.Errorf(errNoValidTaskIDs)
}
// Poll for image URLs
imageURLs := pollTaskStatus(c, client, taskIDs, cookie)
if len(imageURLs) == 0 {
logger.Warnf(ctx, "No image URLs received, retrying with next cookie")
continue
}
// Create response object
result := &model.OpenAIImagesGenerationResponse{
Created: time.Now().Unix(),
Data: make([]*model.OpenAIImagesGenerationDataResponse, 0, len(imageURLs)),
}
// Process image URLs
for _, url := range imageURLs {
data := &model.OpenAIImagesGenerationDataResponse{
URL: url,
RevisedPrompt: openAIReq.Prompt,
}
if openAIReq.ResponseFormat == "b64_json" {
base64Str, err := getBase64ByUrl(data.URL)
if err != nil {
logger.Errorf(ctx, "getBase64ByUrl error: %v", err)
continue
}
data.B64Json = "data:image/webp;base64," + base64Str
}
result.Data = append(result.Data, data)
}
// Handle successful case
if len(result.Data) > 0 {
// Delete temporary session if needed
if config.AutoDelChat == 1 {
go func() {
client := cycletls.Init()
defer safeClose(client)
makeDeleteRequest(client, cookie, projectId)
}()
}
return result, nil
}
}
// All retries exhausted
logger.Errorf(ctx, "All cookies exhausted after %d attempts", maxRetries)
return nil, fmt.Errorf("all cookies are temporarily unavailable")
}
func extractTaskIDs(responseBody string) (string, []string) {
var taskIDs []string
var projectId string
// 分行处理响应
lines := strings.Split(responseBody, "\n")
for _, line := range lines {
// 找到包含project_id的行
if strings.Contains(line, "project_start") {
// 去掉"data: "前缀
jsonStr := strings.TrimPrefix(line, "data: ")
// 解析JSON
var jsonResp struct {
ProjectID string `json:"id"`
}
if err := json.Unmarshal([]byte(jsonStr), &jsonResp); err != nil {
continue
}
// 保存project_id
projectId = jsonResp.ProjectID
}
// 找到包含task_id的行
if strings.Contains(line, "task_id") {
// 去掉"data: "前缀
jsonStr := strings.TrimPrefix(line, "data: ")
// 解析外层JSON
var outerJSON struct {
Content string `json:"content"`
}
if err := json.Unmarshal([]byte(jsonStr), &outerJSON); err != nil {
continue
}
// 解析内层JSON (content字段)
var innerJSON struct {
GeneratedImages []struct {
TaskID string `json:"task_id"`
} `json:"generated_images"`
}
if err := json.Unmarshal([]byte(outerJSON.Content), &innerJSON); err != nil {
continue
}
// 提取所有task_id
for _, img := range innerJSON.GeneratedImages {
if img.TaskID != "" {
taskIDs = append(taskIDs, img.TaskID)
}
}
}
}
return projectId, taskIDs
}
func pollTaskStatus(c *gin.Context, client cycletls.CycleTLS, taskIDs []string, cookie string) []string {
var imageURLs []string
requestData := map[string]interface{}{
"task_ids": taskIDs,
}
jsonData, err := json.Marshal(requestData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to marshal request data"})
return imageURLs
}
sseChan, err := client.DoSSE("https://www.genspark.ai/api/ig_tasks_status", cycletls.Options{
Timeout: 10 * 60 * 60,
Proxy: config.ProxyUrl, // 在每个请求中设置代理
Body: string(jsonData),
Method: "POST",
Headers: map[string]string{
"Content-Type": "application/json",
"Accept": "*/*",
"Origin": baseURL,
"Referer": baseURL + "/",
"Cookie": cookie,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
},
}, "POST")
if err != nil {
logger.Errorf(c, "Failed to make stream request: %v", err)
return imageURLs
}
for response := range sseChan {
if response.Done {
//logger.Warnf(c.Request.Context(), response.Data)
return imageURLs
}
data := response.Data
if data == "" {
continue
}
logger.Debug(c.Request.Context(), strings.TrimSpace(data))
var responseData map[string]interface{}
if err := json.Unmarshal([]byte(data), &responseData); err != nil {
continue
}
if responseData["type"] == "TASKS_STATUS_COMPLETE" {
if finalStatus, ok := responseData["final_status"].(map[string]interface{}); ok {
for _, taskID := range taskIDs {
if task, exists := finalStatus[taskID].(map[string]interface{}); exists {
if status, ok := task["status"].(string); ok && status == "SUCCESS" {
if urls, ok := task["image_urls"].([]interface{}); ok && len(urls) > 0 {
if imageURL, ok := urls[0].(string); ok {
imageURLs = append(imageURLs, imageURL)
}
}
}
}
}
}
}
}
return imageURLs
}
func getBase64ByUrl(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", fmt.Errorf("failed to fetch image: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("received non-200 status code: %d", resp.StatusCode)
}
imgData, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to read image data: %w", err)
}
// Encode the image data to Base64
base64Str := base64.StdEncoding.EncodeToString(imgData)
return base64Str, nil
}
func safeClose(client cycletls.CycleTLS) {
if client.ReqChan != nil {
close(client.ReqChan)
}
if client.RespChan != nil {
close(client.RespChan)
}
}
================================================
FILE: controller/video.go
================================================
package controller
import (
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"genspark2api/common"
"genspark2api/common/config"
logger "genspark2api/common/loggger"
"genspark2api/model"
"github.com/deanxv/CycleTLS/cycletls"
"github.com/gin-gonic/gin"
"github.com/samber/lo"
"io"
"net/http"
"strings"
"time"
)
func VideosForOpenAI(c *gin.Context) {
client := cycletls.Init()
defer safeClose(client)
var openAIReq model.VideosGenerationRequest
if err := c.BindJSON(&openAIReq); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if lo.Contains(common.VideoModelList, openAIReq.Model) == false {
c.JSON(400, gin.H{"error": "Invalid model"})
return
}
resp, err := VideoProcess(c, client, openAIReq)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("VideoProcess err %v\n", err))
c.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: err.Error(),
Type: "request_error",
Code: "500",
},
})
return
} else {
c.JSON(200, resp)
}
}
func VideoProcess(c *gin.Context, client cycletls.CycleTLS, openAIReq model.VideosGenerationRequest) (*model.VideosGenerationResponse, error) {
const (
errNoValidCookies = "No valid cookies available"
errServerErrMsg = "An error occurred with the current request, please try again"
errNoValidTaskIDs = "No valid task IDs received"
)
var (
maxRetries int
cookie string
chatId string
)
cookieManager := config.NewCookieManager()
ctx := c.Request.Context()
// Initialize session manager and get initial cookie
if len(config.SessionImageChatMap) == 0 {
//logger.Warnf(ctx, "未配置环境变量 SESSION_IMAGE_CHAT_MAP, 可能会生图失败!")
maxRetries = len(cookieManager.Cookies)
var err error
cookie, err = cookieManager.GetRandomCookie()
if err != nil {
logger.Errorf(ctx, "Failed to get initial cookie: %v", err)
return nil, fmt.Errorf(errNoValidCookies)
}
}
for attempt := 0; attempt < maxRetries; attempt++ {
// Create request body
requestBody, err := createVideoRequestBody(c, cookie, &openAIReq, chatId)
if err != nil {
logger.Errorf(ctx, "Failed to create request body: %v", err)
return nil, err
}
// Marshal request body
jsonData, err := json.Marshal(requestBody)
if err != nil {
logger.Errorf(ctx, "Failed to marshal request body: %v", err)
return nil, err
}
// Make request
response, err := makeVideoRequest(client, jsonData, cookie)
if err != nil {
logger.Errorf(ctx, "Failed to make video request: %v", err)
return nil, err
}
body := response.Body
switch {
case common.IsRateLimit(body):
logger.Warnf(ctx, "Cookie rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
config.AddRateLimitCookie(cookie, time.Now().Add(time.Duration(config.RateLimitCookieLockDuration)*time.Second))
cookie, err = cookieManager.GetNextCookie()
if err != nil {
logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
return nil, fmt.Errorf(errNoValidCookies)
}
continue
case common.IsFreeLimit(body):
logger.Warnf(ctx, "Cookie free rate limited, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
config.AddRateLimitCookie(cookie, time.Now().Add(24*60*60*time.Second))
cookie, err = cookieManager.GetNextCookie()
if err != nil {
logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
return nil, fmt.Errorf(errNoValidCookies)
}
continue
case common.IsNotLogin(body):
logger.Warnf(ctx, "Cookie Not Login, switching to next cookie, attempt %d/%d, COOKIE:%s", attempt+1, maxRetries, cookie)
cookie, err = cookieManager.GetNextCookie()
if err != nil {
logger.Errorf(ctx, "No more valid cookies available after attempt %d", attempt+1)
c.JSON(http.StatusInternalServerError, gin.H{"error": errNoValidCookies})
return nil, fmt.Errorf(errNoValidCookies)
}
continue
case common.IsServerError(body):
logger.Errorf(ctx, errServerErrMsg)
return nil, fmt.Errorf(errServerErrMsg)
case common.IsServerOverloaded(body):
logger.Errorf(ctx, fmt.Sprintf("Server overloaded, please try again later.%s", "官方服务超载"))
return nil, fmt.Errorf("Server overloaded, please try again later.")
}
projectId, taskIDs := extractVideoTaskIDs(response.Body)
if len(taskIDs) == 0 {
logger.Errorf(ctx, "Response body: %s", response.Body)
return nil, fmt.Errorf(errNoValidTaskIDs)
}
// Poll for image URLs
imageURLs := pollVideoTaskStatus(c, client, taskIDs, cookie)
if len(imageURLs) == 0 {
logger.Warnf(ctx, "No image URLs received, retrying with next cookie")
continue
}
// Create response object
result := &model.VideosGenerationResponse{
Created: time.Now().Unix(),
Data: make([]*model.VideosGenerationDataResponse, 0, len(imageURLs)),
}
// Process image URLs
for _, url := range imageURLs {
data := &model.VideosGenerationDataResponse{
URL: url,
RevisedPrompt: openAIReq.Prompt,
}
//if openAIReq.ResponseFormat == "b64_json" {
// base64Str, err := getBase64ByUrl(data.URL)
// if err != nil {
// logger.Errorf(ctx, "getBase64ByUrl error: %v", err)
// continue
// }
// data.B64Json = "data:image/webp;base64," + base64Str
//}
result.Data = append(result.Data, data)
}
// Handle successful case
if len(result.Data) > 0 {
// Delete temporary session if needed
if config.AutoDelChat == 1 {
go func() {
client := cycletls.Init()
defer safeClose(client)
makeDeleteRequest(client, cookie, projectId)
}()
}
return result, nil
}
}
// All retries exhausted
logger.Errorf(ctx, "All cookies exhausted after %d attempts", maxRetries)
return nil, fmt.Errorf("all cookies are temporarily unavailable")
}
func createVideoRequestBody(c *gin.Context, cookie string, openAIReq *model.VideosGenerationRequest, chatId string) (map[string]interface{}, error) {
// 创建模型配置
modelConfigs := []map[string]interface{}{
{
"model": openAIReq.Model,
"aspect_ratio": openAIReq.AspectRatio,
"reflection_enabled": openAIReq.AutoPrompt,
"duration": openAIReq.Duration,
},
}
// 创建消息数组
var messages []map[string]interface{}
if openAIReq.Image != "" {
var base64Data string
if strings.HasPrefix(openAIReq.Image, "http://") || strings.HasPrefix(openAIReq.Image, "https://") {
// 下载文件
bytes, err := fetchImageBytes(openAIReq.Image)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("fetchImageBytes err %v\n", err))
return nil, fmt.Errorf("fetchImageBytes err %v\n", err)
}
contentType := http.DetectContentType(bytes)
if strings.HasPrefix(contentType, "image/") {
// 是图片类型,转换为base64
base64Data = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(bytes)
}
} else if common.IsImageBase64(openAIReq.Image) {
// 如果已经是 base64 格式
if !strings.HasPrefix(openAIReq.Image, "data:image") {
base64Data = "data:image/jpeg;base64," + openAIReq.Image
} else {
base64Data = openAIReq.Image
}
}
// 构建包含图片的消息
if base64Data != "" {
messages = []map[string]interface{}{
{
"role": "user",
"content": []map[string]interface{}{
{
"type": "image_url",
"image_url": map[string]interface{}{
"url": base64Data,
},
},
{
"type": "text",
"text": openAIReq.Prompt,
},
},
},
}
}
}
// 如果没有图片或处理图片失败,使用纯文本消息
if len(messages) == 0 {
messages = []map[string]interface{}{
{
"role": "user",
"content": openAIReq.Prompt,
},
}
}
var currentQueryString string
if len(chatId) != 0 {
currentQueryString = fmt.Sprintf("id=%s&type=%s", chatId, videoType)
} else {
currentQueryString = fmt.Sprintf("type=%s", videoType)
}
// 创建请求体
requestBody := map[string]interface{}{
"type": "COPILOT_MOA_VIDEO",
//"current_query_string": "type=COPILOT_MOA_IMAGE",
"current_query_string": currentQueryString,
"messages": messages,
"user_s_input": openAIReq.Prompt,
"action_params": map[string]interface{}{},
"extra_data": map[string]interface{}{
"model_configs": modelConfigs,
"imageModelMap": map[string]interface{}{},
},
}
logger.Debug(c.Request.Context(), fmt.Sprintf("RequestBody: %v", requestBody))
if strings.TrimSpace(config.RecaptchaProxyUrl) == "" ||
(!strings.HasPrefix(config.RecaptchaProxyUrl, "http://") &&
!strings.HasPrefix(config.RecaptchaProxyUrl, "https://")) {
return requestBody, nil
} else {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
// 检查并补充 RecaptchaProxyUrl 的末尾斜杠
if !strings.HasSuffix(config.RecaptchaProxyUrl, "/") {
config.RecaptchaProxyUrl += "/"
}
// 创建请求
req, err := http.NewRequest("GET", fmt.Sprintf("%sgenspark", config.RecaptchaProxyUrl), nil)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("创建/genspark请求失败 %v\n", err))
return nil, err
}
// 设置请求头
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Cookie", cookie)
// 发送请求
resp, err := client.Do(req)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("发送/genspark请求失败 %v\n", err))
return nil, err
}
defer resp.Body.Close()
// 读取响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark响应失败 %v\n", err))
return nil, err
}
type Response struct {
Code int `json:"code"`
Token string `json:"token"`
Message string `json:"message"`
}
if resp.StatusCode == 200 {
var response Response
if err := json.Unmarshal(body, &response); err != nil {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark JSON 失败 %v\n", err))
return nil, err
}
if response.Code == 200 {
logger.Debugf(c.Request.Context(), fmt.Sprintf("g_recaptcha_token: %v\n", response.Token))
requestBody["g_recaptcha_token"] = response.Token
logger.Infof(c.Request.Context(), fmt.Sprintf("cheat success!"))
return requestBody, nil
} else {
logger.Errorf(c.Request.Context(), fmt.Sprintf("读取/genspark token 失败 %v\n", err))
return nil, err
}
} else {
logger.Errorf(c.Request.Context(), fmt.Sprintf("请求/genspark失败 %v\n", err))
return nil, err
}
}
}
func makeVideoRequest(client cycletls.CycleTLS, jsonData []byte, cookie string) (cycletls.Response, error) {
accept := "*/*"
return client.Do(apiEndpoint, cycletls.Options{
UserAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
Timeout: 10 * 60 * 60,
Proxy: config.ProxyUrl, // 在每个请求中设置代理
Body: string(jsonData),
Method: "POST",
Headers: map[string]string{
"Content-Type": "application/json",
"Accept": accept,
"Origin": baseURL,
"Referer": baseURL + "/",
"Cookie": cookie,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
},
}, "POST")
}
func extractVideoTaskIDs(responseBody string) (string, []string) {
var taskIDs []string
var projectId string
// 分行处理响应
lines := strings.Split(responseBody, "\n")
for _, line := range lines {
// 找到包含project_id的行
if strings.Contains(line, "project_start") {
// 去掉"data: "前缀
jsonStr := strings.TrimPrefix(line, "data: ")
// 解析JSON
var jsonResp struct {
ProjectID string `json:"id"`
}
if err := json.Unmarshal([]byte(jsonStr), &jsonResp); err != nil {
continue
}
// 保存project_id
projectId = jsonResp.ProjectID
}
// 找到包含task_id的行
if strings.Contains(line, "task_id") {
// 去掉"data: "前缀
jsonStr := strings.TrimPrefix(line, "data: ")
// 解析外层JSON
var outerJSON struct {
Content string `json:"content"`
}
if err := json.Unmarshal([]byte(jsonStr), &outerJSON); err != nil {
continue
}
// 解析内层JSON (content字段)
var innerJSON struct {
GeneratedVideos []struct {
TaskID string `json:"task_id"`
} `json:"generated_videos"`
}
if err := json.Unmarshal([]byte(outerJSON.Content), &innerJSON); err != nil {
continue
}
// 提取所有task_id
for _, img := range innerJSON.GeneratedVideos {
if img.TaskID != "" {
taskIDs = append(taskIDs, img.TaskID)
}
}
}
}
return projectId, taskIDs
}
func pollVideoTaskStatus(c *gin.Context, client cycletls.CycleTLS, taskIDs []string, cookie string) []string {
var imageURLs []string
requestData := map[string]interface{}{
"task_ids": taskIDs,
}
jsonData, err := json.Marshal(requestData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to marshal request data"})
return imageURLs
}
sseChan, err := client.DoSSE("https://www.genspark.ai/api/vg_tasks_status", cycletls.Options{
Timeout: 10 * 60 * 60,
Proxy: config.ProxyUrl, // 在每个请求中设置代理
Body: string(jsonData),
Method: "POST",
Headers: map[string]string{
"Content-Type": "application/json",
"Accept": "*/*",
"Origin": baseURL,
"Referer": baseURL + "/",
"Cookie": cookie,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome",
},
}, "POST")
if err != nil {
logger.Errorf(c, "Failed to make stream request: %v", err)
return imageURLs
}
for response := range sseChan {
if response.Done {
//logger.Warnf(c.Request.Context(), response.Data)
return imageURLs
}
data := response.Data
if data == "" {
continue
}
logger.Debug(c.Request.Context(), strings.TrimSpace(data))
var responseData map[string]interface{}
if err := json.Unmarshal([]byte(data), &responseData); err != nil {
continue
}
if responseData["type"] == "TASKS_STATUS_COMPLETE" {
if finalStatus, ok := responseData["final_status"].(map[string]interface{}); ok {
for _, taskID := range taskIDs {
if task, exists := finalStatus[taskID].(map[string]interface{}); exists {
if status, ok := task["status"].(string); ok && status == "SUCCESS" {
if urls, ok := task["video_urls"].([]interface{}); ok && len(urls) > 0 {
if imageURL, ok := urls[0].(string); ok {
imageURLs = append(imageURLs, imageURL)
}
}
}
}
}
}
}
}
return imageURLs
}
================================================
FILE: docker-compose.yml
================================================
version: '3.4'
services:
genspark2api:
image: deanxv/genspark2api:latest
container_name: genspark2api
restart: always
ports:
- "7055:7055"
volumes:
- ./data:/app/genspark2api/data
environment:
- GS_COOKIE=****** # cookie (多个请以,分隔)
- API_SECRET=123456 # [可选]接口密钥-修改此行为请求头校验的值(多个请以,分隔)
- TZ=Asia/Shanghai
================================================
FILE: go.mod
================================================
module genspark2api
go 1.23.0
toolchain go1.23.2
require (
github.com/deanxv/CycleTLS/cycletls v0.0.0-20250208071223-7956a8a6a221
github.com/gin-contrib/cors v1.7.3
github.com/gin-gonic/gin v1.10.0
github.com/google/uuid v1.6.0
github.com/json-iterator/go v1.1.12
github.com/pkoukk/tiktoken-go v0.1.7
github.com/samber/lo v1.49.1
)
require (
github.com/Danny-Dasilva/fhttp v0.0.0-20240217042913-eeeb0b347ce1 // indirect
github.com/andybalholm/brotli v1.1.1 // indirect
github.com/bytedance/sonic v1.12.9 // indirect
github.com/bytedance/sonic/loader v0.2.3 // indirect
github.com/cloudflare/circl v1.6.0 // indirect
github.com/cloudwego/base64x v0.1.5 // indirect
github.com/dlclark/regexp2 v1.11.5 // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/gin-contrib/sse v1.0.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.25.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/refraction-networking/utls v1.6.7 // indirect
github.com/rogpeppe/go-internal v1.11.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.14.0 // indirect
golang.org/x/crypto v0.35.0 // indirect
golang.org/x/net v0.35.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/text v0.22.0 // indirect
google.golang.org/protobuf v1.36.5 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
h12.io/socks v1.0.3 // indirect
)
================================================
FILE: go.sum
================================================
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.37.0/go.mod h1:TS1dMSSfndXH133OKGwekG838Om/cQT0BUHV3HcBgoo=
dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU=
dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU=
dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4=
dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU=
git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Danny-Dasilva/fhttp v0.0.0-20240217042913-eeeb0b347ce1 h1:/lqhaiz7xdPr6kuaW1tQ/8DdpWdxkdyd9W/6EHz4oRw=
github.com/Danny-Dasilva/fhttp v0.0.0-20240217042913-eeeb0b347ce1/go.mod h1:Hvab/V/YKCDXsEpKYKHjAXH5IFOmoq9FsfxjztEqvDc=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g=
github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s=
github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
github.com/bytedance/sonic v1.12.9 h1:Od1BvK55NnewtGaJsTDeAOSnLVO2BTSLOe0+ooKokmQ=
github.com/bytedance/sonic v1.12.9/go.mod h1:uVvFidNmlt9+wa31S1urfwwthTWteBgG0hWuoKAXTx8=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/bytedance/sonic/loader v0.2.3 h1:yctD0Q3v2NOGfSWPLPvG2ggA2kV6TS6s4wioyEqssH0=
github.com/bytedance/sonic/loader v0.2.3/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cloudflare/circl v1.3.3/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA=
github.com/cloudflare/circl v1.6.0 h1:cr5JKic4HI+LkINy2lg3W2jF8sHCVTBncJr5gIIq7qk=
github.com/cloudflare/circl v1.6.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/deanxv/CycleTLS/cycletls v0.0.0-20250208071223-7956a8a6a221 h1:zykIpPFKX7DsNfsK3UpwN78oec/x9fND1hZrib7zod8=
github.com/deanxv/CycleTLS/cycletls v0.0.0-20250208071223-7956a8a6a221/go.mod h1:eAyIp7Lbyq6WnJDGicqf7nYr0bTj5FQ0HXQbIesuuJ8=
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
github.com/francoispqt/gojay v1.2.13/go.mod h1:ehT5mTG4ua4581f1++1WLG0vPdaA9HaiDsoyrBGkyDY=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/gaukas/godicttls v0.0.4/go.mod h1:l6EenT4TLWgTdwslVb4sEMOCf7Bv0JAK67deKr9/NCI=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/gin-contrib/cors v1.7.3 h1:hV+a5xp8hwJoTw7OY+a70FsL8JkVVFTXw9EcfrYUdns=
github.com/gin-contrib/cors v1.7.3/go.mod h1:M3bcKZhxzsvI+rlRSkkxHyljJt1ESd93COUvemZ79j4=
github.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E=
github.com/gin-contrib/sse v1.0.0/go.mod h1:zNuFdwarAygJBht0NTKiSi3jRf6RbqeILZ9Sp6Slhe0=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0=
github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=
github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.25.0 h1:5Dh7cjvzR7BRZadnsVOzPhWsrwUr0nmsZJxEAnFLNO8=
github.com/go-playground/validator/v10 v10.25.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY=
github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw=
github.com/h12w/go-socks5 v0.0.0-20200522160539-76189e178364 h1:5XxdakFhqd9dnXoAZy1Mb2R/DZ6D1e+0bGC/JhucGYI=
github.com/h12w/go-socks5 v0.0.0-20200522160539-76189e178364/go.mod h1:eDJQioIyy4Yn3MVivT7rv/39gAJTrA7lgmYr8EW950c=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo=
github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=
github.com/onsi/ginkgo/v2 v2.1.4/go.mod h1:um6tUpWM/cxCK3/FK8BXqEiUMUwRgSM4JXG47RKZmLU=
github.com/onsi/ginkgo/v2 v2.1.6/go.mod h1:MEH45j8TBi6u9BMogfbp0stKC5cdGjumZj5Y7AG4VIk=
github.com/onsi/ginkgo/v2 v2.2.0/go.mod h1:MEH45j8TBi6u9BMogfbp0stKC5cdGjumZj5Y7AG4VIk=
github.com/onsi/ginkgo/v2 v2.3.0/go.mod h1:Eew0uilEqZmIEZr8JrvYlvOM7Rr6xzTmMV8AyFNU9d0=
github.com/onsi/ginkgo/v2 v2.4.0/go.mod h1:iHkDK1fKGcBoEHT5W7YBq4RFWaQulw+caOMkAt4OrFo=
github.com/onsi/ginkgo/v2 v2.5.0/go.mod h1:Luc4sArBICYCS8THh8v3i3i5CuSZO+RaQRaJoeNwomw=
github.com/onsi/ginkgo/v2 v2.7.0/go.mod h1:yjiuMwPokqY1XauOgju45q3sJt6VzQ/Fict1LFVcsAo=
github.com/onsi/ginkgo/v2 v2.8.1/go.mod h1:N1/NbDngAFcSLdyZ+/aYTYGSlq9qMCS/cNKGJjy+csc=
github.com/onsi/ginkgo/v2 v2.9.0/go.mod h1:4xkjoL/tZv4SMWeww56BU5kAt19mVB47gTWxmrTcxyk=
github.com/onsi/ginkgo/v2 v2.9.1/go.mod h1:FEcmzVcCHl+4o9bQZVab+4dC9+j+91t2FHSzmGAPfuo=
github.com/onsi/ginkgo/v2 v2.9.2/go.mod h1:WHcJJG2dIlcCqVfBAwUCrJxSPFb6v4azBwgxeMeDuts=
github.com/onsi/ginkgo/v2 v2.9.5/go.mod h1:tvAoo1QUJwNEU2ITftXTpR7R1RbCzoZUOs3RonqW57k=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro=
github.com/onsi/gomega v1.20.1/go.mod h1:DtrZpjmvpn2mPm4YWQa0/ALMDj9v4YxLgojwPeREyVo=
github.com/onsi/gomega v1.21.1/go.mod h1:iYAIXgPSaDHak0LCMA+AWBpIKBr8WZicMxnE8luStNc=
github.com/onsi/gomega v1.22.1/go.mod h1:x6n7VNe4hw0vkyYUM4mjIXx3JbLiPaBPNgB7PRQ1tuM=
github.com/onsi/gomega v1.24.0/go.mod h1:Z/NWtiqwBrwUt4/2loMmHL63EDLnYHmVbuBpDr2vQAg=
github.com/onsi/gomega v1.24.1/go.mod h1:3AOiACssS3/MajrniINInwbfOOtfZvplPzuRSmvt1jM=
github.com/onsi/gomega v1.26.0/go.mod h1:r+zV744Re+DiYCIPRlYOTxn0YkOLcAnW8k1xXdMPGhM=
github.com/onsi/gomega v1.27.1/go.mod h1:aHX5xOykVYzWOV4WqQy0sy8BQptgukenXpCXfadcIAw=
github.com/onsi/gomega v1.27.3/go.mod h1:5vG284IBtfDAmDyrK+eGyZmUgUlmi+Wngqo557cZ6Gw=
github.com/onsi/gomega v1.27.4/go.mod h1:riYq/GJKh8hhoM01HN6Vmuy93AarCXCBGpvFDK3q3fQ=
github.com/onsi/gomega v1.27.6/go.mod h1:PIQNjfQwkP3aQAH7lf7j87O/5FiNr+ZR8+ipb+qQlhg=
github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8=
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2 h1:JhzVVoYvbOACxoUmOs6V/G4D5nPVUW73rKvXxP4XUJc=
github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2/go.mod h1:iIss55rKnNBTvrwdmkUpLnDpZoAHvWaiq5+iMmen4AE=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkoukk/tiktoken-go v0.1.7 h1:qOBHXX4PHtvIvmOtyg1EeKlwFRiMKAcoMp4Q+bLQDmw=
github.com/pkoukk/tiktoken-go v0.1.7/go.mod h1:9NiV+i9mJKGj1rYOT+njbv+ZwA/zJxYdewGl6qVatpg=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/quic-go/qpack v0.4.0/go.mod h1:UZVnYIfi5GRk+zI9UMaCPsmZ2xKJP7XBUvVyT1Knj9A=
github.com/quic-go/qtls-go1-20 v0.3.1/go.mod h1:X9Nh97ZL80Z+bX/gUXMbipO6OxdiDi58b/fMC9mAL+k=
github.com/quic-go/quic-go v0.37.4/go.mod h1:YsbH1r4mSHPJcLF4k4zruUkLBqctEMBDR6VPvcYjIsU=
github.com/refraction-networking/utls v1.5.4/go.mod h1:SPuDbBmgLGp8s+HLNc83FuavwZCFoMmExj+ltUHiHUw=
github.com/refraction-networking/utls v1.6.7 h1:zVJ7sP1dJx/WtVuITug3qYUq034cDq9B2MR1K67ULZM=
github.com/refraction-networking/utls v1.6.7/go.mod h1:BC3O4vQzye5hqpmDTWUqi4P5DDhzJfkV1tdqtawQIH0=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
github.com/samber/lo v1.49.1 h1:4BIFyVfuQSEpluc7Fua+j1NolZHiEHEpaSEKdsH0tew=
github.com/samber/lo v1.49.1/go.mod h1:dO6KHFzUKXgP8LDhU0oI8d2hekjXnGOu0DB8Jecxd6o=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY=
github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM=
github.com/shurcooL/github_flavored_markdown v0.0.0-20181002035957-2122de532470/go.mod h1:2dOwnU2uBioM+SGy2aZoq1f/Sd1l9OkAeAUvjSyvgU0=
github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk=
github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ=
github.com/shurcooL/gofontwoff v0.0.0-20180329035133-29b52fc0a18d/go.mod h1:05UtEgK5zq39gLST6uB0cf3NEHjETfB4Fgr3Gx5R9Vw=
github.com/shurcooL/gopherjslib v0.0.0-20160914041154-feb6d3990c2c/go.mod h1:8d3azKNyqcHP1GaQE/c6dDgjkgSx2BZ4IoEi4F1reUI=
github.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:ZpfEhSmds4ytuByIcDnOLkTHGUI6KNqRNPDLHDk+mUU=
github.com/shurcooL/highlight_go v0.0.0-20181028180052-98c3abbbae20/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag=
github.com/shurcooL/home v0.0.0-20181020052607-80b7ffcb30f9/go.mod h1:+rgNQw2P9ARFAs37qieuu7ohDNQ3gds9msbT2yn85sg=
github.com/shurcooL/htmlg v0.0.0-20170918183704-d01228ac9e50/go.mod h1:zPn1wHpTIePGnXSHpsVPWEktKXHr6+SS6x/IKRb7cpw=
github.com/shurcooL/httperror v0.0.0-20170206035902-86b7830d14cc/go.mod h1:aYMfkZ6DWSJPJ6c4Wwz3QtW22G7mf/PEgaB9k/ik5+Y=
github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg=
github.com/shurcooL/httpgzip v0.0.0-20180522190206-b1c53ac65af9/go.mod h1:919LwcH0M7/W4fcZ0/jy0qGght1GIhqyS/EgWGH2j5Q=
github.com/shurcooL/issues v0.0.0-20181008053335-6292fdc1e191/go.mod h1:e2qWDig5bLteJ4fwvDAc2NHzqFEthkqn7aOZAOpj+PQ=
github.com/shurcooL/issuesapp v0.0.0-20180602232740-048589ce2241/go.mod h1:NPpHK2TI7iSaM0buivtFUc9offApnI0Alt/K8hcHy0I=
github.com/shurcooL/notifications v0.0.0-20181007000457-627ab5aea122/go.mod h1:b5uSkrEVM1jQUspwbixRBhaIjIzL2xazXp6kntxYle0=
github.com/shurcooL/octicon v0.0.0-20181028054416-fa4f57f9efb2/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ=
github.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1lToEk4d2s07G3XGfz2QrgHXg4RJBvjrOozvoWfk=
github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4=
github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw=
github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE=
github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrw
gitextract_kz2qbgc6/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ ├── config.yml
│ │ └── feature_request.md
│ ├── close_issue.py
│ └── workflows/
│ ├── CloseIssue.yml
│ ├── docker-image-amd64.yml
│ ├── docker-image-arm64.yml
│ ├── github-pages.yml
│ ├── linux-release.yml
│ ├── macos-release.yml
│ └── windows-release.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── check/
│ └── check.go
├── common/
│ ├── config/
│ │ └── config.go
│ ├── constants.go
│ ├── env/
│ │ └── helper.go
│ ├── helper/
│ │ ├── helper.go
│ │ ├── key.go
│ │ └── time.go
│ ├── init.go
│ ├── loggger/
│ │ ├── constants.go
│ │ └── logger.go
│ ├── random/
│ │ └── main.go
│ ├── rate-limit.go
│ ├── token.go
│ └── utils.go
├── controller/
│ ├── api.go
│ ├── chat.go
│ └── video.go
├── docker-compose.yml
├── go.mod
├── go.sum
├── job/
│ └── cookie.go
├── main.go
├── middleware/
│ ├── auth.go
│ ├── cors.go
│ ├── ip-list.go
│ ├── logger.go
│ ├── rate-limit.go
│ └── request-id.go
├── model/
│ └── openai.go
├── router/
│ ├── api-router.go
│ └── main.go
└── yescaptcha/
└── main.go
SYMBOL INDEX (222 symbols across 28 files)
FILE: .github/close_issue.py
function get_stargazers (line 14) | def get_stargazers(repo):
function get_issues (line 40) | def get_issues(repo):
function close_issue (line 68) | def close_issue(repo, issue_number):
function lock_issue (line 82) | def lock_issue(repo, issue_number):
FILE: check/check.go
function CheckEnvVariable (line 12) | func CheckEnvVariable() {
FILE: common/config/config.go
type RateLimitCookie (line 67) | type RateLimitCookie struct
function AddRateLimitCookie (line 75) | func AddRateLimitCookie(cookie string, expirationTime time.Time) {
type CookieManager (line 82) | type CookieManager struct
method RemoveCookie (line 185) | func (cm *CookieManager) RemoveCookie(cookieToRemove string) error {
method GetNextCookie (line 218) | func (cm *CookieManager) GetNextCookie() (string, error) {
method GetRandomCookie (line 230) | func (cm *CookieManager) GetRandomCookie() (string, error) {
function InitGSCookies (line 94) | func InitGSCookies() {
function RemoveCookie (line 115) | func RemoveCookie(cookieToRemove string) {
function GetGSCookies (line 132) | func GetGSCookies() []string {
function NewCookieManager (line 143) | func NewCookieManager() *CookieManager {
function IsRateLimited (line 177) | func IsRateLimited(cookie string) bool {
type SessionKey (line 247) | type SessionKey struct
type SessionManager (line 253) | type SessionManager struct
method AddSession (line 266) | func (sm *SessionManager) AddSession(cookie string, model string, chat...
method GetChatID (line 278) | func (sm *SessionManager) GetChatID(cookie string, model string) (stri...
method DeleteSession (line 291) | func (sm *SessionManager) DeleteSession(cookie string, model string) {
method GetChatIDsByCookie (line 303) | func (sm *SessionManager) GetChatIDsByCookie(cookie string) []string {
function NewSessionManager (line 259) | func NewSessionManager() *SessionManager {
type SessionMapManager (line 316) | type SessionMapManager struct
method GetCurrentKeyValue (line 338) | func (sm *SessionMapManager) GetCurrentKeyValue() (string, string, err...
method GetNextKeyValue (line 351) | func (sm *SessionMapManager) GetNextKeyValue() (string, string, error) {
method GetRandomKeyValue (line 365) | func (sm *SessionMapManager) GetRandomKeyValue() (string, string, erro...
method AddKeyValue (line 380) | func (sm *SessionMapManager) AddKeyValue(key, value string) {
method RemoveKey (line 392) | func (sm *SessionMapManager) RemoveKey(key string) {
method GetSize (line 418) | func (sm *SessionMapManager) GetSize() int {
function NewSessionMapManager (line 323) | func NewSessionMapManager() *SessionMapManager {
FILE: common/env/helper.go
function Bool (line 8) | func Bool(env string, defaultValue bool) bool {
function Int (line 15) | func Int(env string, defaultValue int) int {
function Float64 (line 26) | func Float64(env string, defaultValue float64) float64 {
function String (line 37) | func String(env string, defaultValue string) string {
FILE: common/helper/helper.go
function OpenBrowser (line 16) | func OpenBrowser(url string) {
function GetIp (line 32) | func GetIp() (ip string) {
function Bytes2Size (line 63) | func Bytes2Size(num int64) string {
function Interface2String (line 81) | func Interface2String(inter interface{}) string {
function UnescapeHTML (line 93) | func UnescapeHTML(x string) interface{} {
function IntMax (line 97) | func IntMax(a int, b int) int {
function GenRequestID (line 105) | func GenRequestID() string {
function GetResponseID (line 109) | func GetResponseID(c *gin.Context) string {
function Max (line 114) | func Max(a int, b int) int {
function AssignOrDefault (line 122) | func AssignOrDefault(value string, defaultValue string) string {
function MessageWithRequestId (line 129) | func MessageWithRequestId(message string, id string) string {
function String2Int (line 133) | func String2Int(str string) int {
FILE: common/helper/key.go
constant RequestIdKey (line 4) | RequestIdKey = "X-Request-Id"
FILE: common/helper/time.go
function GetTimestamp (line 8) | func GetTimestamp() int64 {
function GetTimeString (line 12) | func GetTimeString() string {
FILE: common/init.go
function printHelp (line 21) | func printHelp() {
function init (line 28) | func init() {
FILE: common/loggger/logger.go
constant loggerDEBUG (line 19) | loggerDEBUG = "DEBUG"
constant loggerINFO (line 20) | loggerINFO = "INFO"
constant loggerWarn (line 21) | loggerWarn = "WARN"
constant loggerError (line 22) | loggerError = "ERR"
function SetupLogger (line 27) | func SetupLogger() {
function SysLog (line 41) | func SysLog(s string) {
function SysError (line 46) | func SysError(s string) {
function Debug (line 51) | func Debug(ctx context.Context, msg string) {
function Info (line 57) | func Info(ctx context.Context, msg string) {
function Warn (line 61) | func Warn(ctx context.Context, msg string) {
function Error (line 65) | func Error(ctx context.Context, msg string) {
function Debugf (line 69) | func Debugf(ctx context.Context, format string, a ...any) {
function Infof (line 73) | func Infof(ctx context.Context, format string, a ...any) {
function Warnf (line 77) | func Warnf(ctx context.Context, format string, a ...any) {
function Errorf (line 81) | func Errorf(ctx context.Context, format string, a ...any) {
function logHelper (line 85) | func logHelper(ctx context.Context, level string, msg string) {
function FatalLog (line 99) | func FatalLog(v ...any) {
FILE: common/random/main.go
function GetUUID (line 10) | func GetUUID() string {
constant keyChars (line 16) | keyChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
constant keyNumbers (line 17) | keyNumbers = "0123456789"
function init (line 19) | func init() {
function GenerateKey (line 23) | func GenerateKey() string {
function GetRandomString (line 40) | func GetRandomString(length int) string {
function GetRandomNumberString (line 49) | func GetRandomNumberString(length int) string {
function RandRange (line 59) | func RandRange(min, max int) int {
FILE: common/rate-limit.go
type InMemoryRateLimiter (line 8) | type InMemoryRateLimiter struct
method Init (line 14) | func (l *InMemoryRateLimiter) Init(expirationDuration time.Duration) {
method clearExpiredItems (line 28) | func (l *InMemoryRateLimiter) clearExpiredItems() {
method Request (line 45) | func (l *InMemoryRateLimiter) Request(key string, maxRequestNum int, d...
FILE: common/token.go
function InitTokenEncoders (line 16) | func InitTokenEncoders() {
function getTokenEncoder (line 45) | func getTokenEncoder(model string) *tiktoken.Tiktoken {
function getTokenNum (line 62) | func getTokenNum(tokenEncoder *tiktoken.Tiktoken, text string) int {
function CountTokenMessages (line 66) | func CountTokenMessages(messages []model.OpenAIChatMessage, model string...
constant lowDetailCost (line 120) | lowDetailCost = 85
constant highDetailCostPerTile (line 121) | highDetailCostPerTile = 170
constant additionalCost (line 122) | additionalCost = 85
constant gpt4oMiniLowDetailCost (line 124) | gpt4oMiniLowDetailCost = 2833
constant gpt4oMiniHighDetailCost (line 125) | gpt4oMiniHighDetailCost = 5667
constant gpt4oMiniAdditionalCost (line 126) | gpt4oMiniAdditionalCost = 2833
function countImageTokens (line 131) | func countImageTokens(url string, detail string, model string) (_ int, e...
function CountTokenInput (line 172) | func CountTokenInput(input any, model string) int {
function CountTokenText (line 186) | func CountTokenText(text string, model string) int {
function CountToken (line 191) | func CountToken(text string) int {
FILE: common/utils.go
function SplitStringByBytes (line 17) | func SplitStringByBytes(s string, size int) []string {
function Obj2Bytes (line 47) | func Obj2Bytes(obj interface{}) ([]byte, error) {
function GetUUID (line 58) | func GetUUID() string {
function RandomElement (line 65) | func RandomElement[T any](slice []T) (T, error) {
function SliceContains (line 79) | func SliceContains(slice []string, str string) bool {
function IsImageBase64 (line 88) | func IsImageBase64(s string) bool {
function IsBase64 (line 110) | func IsBase64(s string) bool {
function IsCloudflareBlock (line 134) | func IsCloudflareBlock(data string) bool {
function IsCloudflareChallenge (line 142) | func IsCloudflareChallenge(data string) bool {
function IsRateLimit (line 171) | func IsRateLimit(data string) bool {
function IsNotLogin (line 179) | func IsNotLogin(data string) bool {
function IsServerError (line 187) | func IsServerError(data string) bool {
function IsServerOverloaded (line 195) | func IsServerOverloaded(data string) bool {
function IsFreeLimit (line 203) | func IsFreeLimit(data string) bool {
function IsServiceUnavailablePage (line 211) | func IsServiceUnavailablePage(data string) bool {
FILE: controller/api.go
function InitModelChatMap (line 9) | func InitModelChatMap(c *gin.Context) {
FILE: controller/chat.go
constant errNoValidCookies (line 24) | errNoValidCookies = "No valid cookies available"
constant baseURL (line 28) | baseURL = "https://www.genspark.ai"
constant apiEndpoint (line 29) | apiEndpoint = baseURL + "/api/copilot/ask"
constant deleteEndpoint (line 30) | deleteEndpoint = baseURL + "/api/project/delete?project_id=%s"
constant uploadEndpoint (line 31) | uploadEndpoint = baseURL + "/api/get_upload_personal_image_url"
constant chatType (line 32) | chatType = "COPILOT_MOA_CHAT"
constant imageType (line 33) | imageType = "COPILOT_MOA_IMAGE"
constant videoType (line 34) | videoType = "COPILOT_MOA_VIDEO"
constant responseIDFormat (line 35) | responseIDFormat = "chatcmpl-%s"
type OpenAIChatMessage (line 38) | type OpenAIChatMessage struct
type OpenAIChatCompletionRequest (line 43) | type OpenAIChatCompletionRequest struct
function ChatForOpenAI (line 49) | func ChatForOpenAI(c *gin.Context) {
function processMessages (line 201) | func processMessages(c *gin.Context, client cycletls.CycleTLS, cookie st...
function processUrl (line 227) | func processUrl(c *gin.Context, client cycletls.CycleTLS, cookie string,...
function processBytes (line 268) | func processBytes(c *gin.Context, client cycletls.CycleTLS, cookie strin...
function fetchImageBytes (line 328) | func fetchImageBytes(url string) ([]byte, error) {
function createRequestBody (line 338) | func createRequestBody(c *gin.Context, client cycletls.CycleTLS, cookie ...
function createImageRequestBody (line 393) | func createImageRequestBody(c *gin.Context, cookie string, openAIReq *mo...
function createStreamResponse (line 567) | func createStreamResponse(responseId, modelName string, jsonData []byte,...
function handleMessageFieldDelta (line 591) | func handleMessageFieldDelta(c *gin.Context, event map[string]interface{...
type Content (line 653) | type Content struct
function getDetailAnswer (line 657) | func getDetailAnswer(eventMap map[string]interface{}) (string, error) {
function handleMessageResult (line 674) | func handleMessageResult(c *gin.Context, event map[string]interface{}, r...
function sendSSEvent (line 696) | func sendSSEvent(c *gin.Context, response model.OpenAIChatCompletionResp...
function makeRequest (line 708) | func makeRequest(client cycletls.CycleTLS, jsonData []byte, cookie strin...
function makeImageRequest (line 731) | func makeImageRequest(client cycletls.CycleTLS, jsonData []byte, cookie ...
function makeDeleteRequest (line 752) | func makeDeleteRequest(client cycletls.CycleTLS, cookie, projectId strin...
function makeGetUploadUrlRequest (line 789) | func makeGetUploadUrlRequest(client cycletls.CycleTLS, cookie string) (c...
function makeUploadRequest (line 824) | func makeUploadRequest(client cycletls.CycleTLS, uploadUrl string, fileB...
function handleStreamRequest (line 862) | func handleStreamRequest(c *gin.Context, client cycletls.CycleTLS, cooki...
function cheat (line 984) | func cheat(requestBody map[string]interface{}, c *gin.Context, cookie st...
function processStreamData (line 1057) | func processStreamData(c *gin.Context, data string, projectId *string, c...
function makeStreamRequest (line 1113) | func makeStreamRequest(c *gin.Context, client cycletls.CycleTLS, jsonDat...
function handleNonStreamRequest (line 1224) | func handleNonStreamRequest(c *gin.Context, client cycletls.CycleTLS, co...
function OpenaiModels (line 1420) | func OpenaiModels(c *gin.Context) {
function ImagesForOpenAI (line 1440) | func ImagesForOpenAI(c *gin.Context) {
function ImageProcess (line 1477) | func ImageProcess(c *gin.Context, client cycletls.CycleTLS, openAIReq mo...
function extractTaskIDs (line 1671) | func extractTaskIDs(responseBody string) (string, []string) {
function pollTaskStatus (line 1730) | func pollTaskStatus(c *gin.Context, client cycletls.CycleTLS, taskIDs []...
function getBase64ByUrl (line 1799) | func getBase64ByUrl(url string) (string, error) {
function safeClose (line 1820) | func safeClose(client cycletls.CycleTLS) {
FILE: controller/video.go
function VideosForOpenAI (line 21) | func VideosForOpenAI(c *gin.Context) {
function VideoProcess (line 54) | func VideoProcess(c *gin.Context, client cycletls.CycleTLS, openAIReq mo...
function createVideoRequestBody (line 202) | func createVideoRequestBody(c *gin.Context, cookie string, openAIReq *mo...
function makeVideoRequest (line 367) | func makeVideoRequest(client cycletls.CycleTLS, jsonData []byte, cookie ...
function extractVideoTaskIDs (line 388) | func extractVideoTaskIDs(responseBody string) (string, []string) {
function pollVideoTaskStatus (line 447) | func pollVideoTaskStatus(c *gin.Context, client cycletls.CycleTLS, taskI...
FILE: job/cookie.go
function LoadCookieTask (line 10) | func LoadCookieTask() {
FILE: main.go
function main (line 17) | func main() {
FILE: middleware/auth.go
function isValidSecret (line 12) | func isValidSecret(secret string) bool {
function authHelper (line 16) | func authHelper(c *gin.Context) {
function authHelperForOpenai (line 30) | func authHelperForOpenai(c *gin.Context) {
function Auth (line 53) | func Auth() func(c *gin.Context) {
function OpenAIAuth (line 59) | func OpenAIAuth() func(c *gin.Context) {
FILE: middleware/cors.go
function CORS (line 8) | func CORS() gin.HandlerFunc {
FILE: middleware/ip-list.go
function IPBlacklistMiddleware (line 11) | func IPBlacklistMiddleware() gin.HandlerFunc {
FILE: middleware/logger.go
function SetUpLogger (line 9) | func SetUpLogger(server *gin.Engine) {
FILE: middleware/rate-limit.go
function memoryRateLimiter (line 14) | func memoryRateLimiter(c *gin.Context, maxRequestNum int, duration int64...
function rateLimitFactory (line 26) | func rateLimitFactory(maxRequestNum int, duration int64, mark string) fu...
function RequestRateLimit (line 34) | func RequestRateLimit() func(c *gin.Context) {
FILE: middleware/request-id.go
function RequestId (line 9) | func RequestId() func(c *gin.Context) {
FILE: model/openai.go
type OpenAIChatCompletionRequest (line 5) | type OpenAIChatCompletionRequest struct
method AddMessage (line 29) | func (r *OpenAIChatCompletionRequest) AddMessage(message OpenAIChatMes...
method PrependMessagesFromJSON (line 33) | func (r *OpenAIChatCompletionRequest) PrependMessagesFromJSON(jsonStri...
method SystemMessagesProcess (line 54) | func (r *OpenAIChatCompletionRequest) SystemMessagesProcess(model stri...
method FilterUserMessage (line 74) | func (r *OpenAIChatCompletionRequest) FilterUserMessage() {
method GetUserContent (line 215) | func (r *OpenAIChatCompletionRequest) GetUserContent() []string {
type OpenAIChatCompletionExtraRequest (line 12) | type OpenAIChatCompletionExtraRequest struct
type SessionState (line 16) | type SessionState struct
type OpenAIChatMessage (line 22) | type OpenAIChatMessage struct
type OpenAIErrorResponse (line 88) | type OpenAIErrorResponse struct
type OpenAIError (line 92) | type OpenAIError struct
type OpenAIChatCompletionResponse (line 99) | type OpenAIChatCompletionResponse struct
type OpenAIChoice (line 110) | type OpenAIChoice struct
type OpenAIMessage (line 118) | type OpenAIMessage struct
type OpenAIUsage (line 123) | type OpenAIUsage struct
type OpenAIDelta (line 129) | type OpenAIDelta struct
type OpenAIImagesGenerationRequest (line 134) | type OpenAIImagesGenerationRequest struct
type VideosGenerationRequest (line 142) | type VideosGenerationRequest struct
type VideosGenerationResponse (line 152) | type VideosGenerationResponse struct
type VideosGenerationDataResponse (line 157) | type VideosGenerationDataResponse struct
type OpenAIImagesGenerationResponse (line 163) | type OpenAIImagesGenerationResponse struct
type OpenAIImagesGenerationDataResponse (line 170) | type OpenAIImagesGenerationDataResponse struct
type OpenAIGPT4VImagesReq (line 176) | type OpenAIGPT4VImagesReq struct
type GetUserContent (line 184) | type GetUserContent interface
type OpenAIModerationRequest (line 188) | type OpenAIModerationRequest struct
type OpenAIModerationResponse (line 192) | type OpenAIModerationResponse struct
type OpenaiModelResponse (line 202) | type OpenaiModelResponse struct
type OpenaiModelListResponse (line 210) | type OpenaiModelListResponse struct
FILE: router/api-router.go
function SetApiRouter (line 12) | func SetApiRouter(router *gin.Engine) {
function ProcessPath (line 30) | func ProcessPath(path string) string {
FILE: router/main.go
function SetRouter (line 7) | func SetRouter(router *gin.Engine) {
FILE: yescaptcha/main.go
constant defaultAPIEndpoint (line 14) | defaultAPIEndpoint = "https://api.yescaptcha.com"
constant createTaskPath (line 15) | createTaskPath = "/createTask"
constant getResultPath (line 16) | getResultPath = "/getTaskResult"
constant maxRetries (line 17) | maxRetries = 20
constant pollingInterval (line 18) | pollingInterval = 3 * time.Second
type Client (line 22) | type Client struct
method SolveRecaptchaV3 (line 104) | func (c *Client) SolveRecaptchaV3(ctx context.Context, req RecaptchaV3...
method createTask (line 113) | func (c *Client) createTask(ctx context.Context, req RecaptchaV3Reques...
method waitForResult (line 161) | func (c *Client) waitForResult(ctx context.Context, taskID string) (st...
method getTaskResult (line 188) | func (c *Client) getTaskResult(ctx context.Context, taskID string) (*g...
type Options (line 29) | type Options struct
function NewClient (line 35) | func NewClient(clientKey string, opts *Options) *Client {
type RecaptchaV3Request (line 55) | type RecaptchaV3Request struct
type createTaskRequest (line 64) | type createTaskRequest struct
type task (line 69) | type task struct
type createTaskResponse (line 79) | type createTaskResponse struct
type getResultRequest (line 86) | type getResultRequest struct
type getResultResponse (line 91) | type getResultResponse struct
type solution (line 99) | type solution struct
Condensed preview — 47 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (263K chars).
[
{
"path": ".github/ISSUE_TEMPLATE/bug_report.md",
"chars": 309,
"preview": "---\nname: 报告问题\nabout: 使用简练详细的语言描述你遇到的问题\ntitle: ''\nlabels: bug\nassignees: ''\n\n---\n\n**温馨提示: 未`star`项目会被自动关闭issue哦!**\n\n**例行"
},
{
"path": ".github/ISSUE_TEMPLATE/config.yml",
"chars": 101,
"preview": "blank_issues_enabled: false\ncontact_links:\n - name: 赞赏支持\n # url:\n about: 请作者喝杯咖啡,以激励作者持续开发\n"
},
{
"path": ".github/ISSUE_TEMPLATE/feature_request.md",
"chars": 286,
"preview": "---\nname: 功能请求\nabout: 使用简练详细的语言描述希望加入的新功能\ntitle: ''\nlabels: enhancement\nassignees: ''\n\n---\n\n**温馨提示: 未`star`项目会被自动关闭issue"
},
{
"path": ".github/close_issue.py",
"chars": 2858,
"preview": "import os\nimport requests\n\nissue_labels = ['no respect']\ngithub_repo = 'deanxv/genspark2api'\ngithub_token = os.getenv(\"G"
},
{
"path": ".github/workflows/CloseIssue.yml",
"chars": 479,
"preview": "name: CloseIssue\n\non:\n workflow_dispatch:\n issues:\n types: [ opened ]\n\njobs:\n run-python-script:\n runs-on: ubun"
},
{
"path": ".github/workflows/docker-image-amd64.yml",
"chars": 1404,
"preview": "name: Publish Docker image (amd64)\n\non:\n push:\n tags:\n - '*'\n workflow_dispatch:\n inputs:\n name:\n "
},
{
"path": ".github/workflows/docker-image-arm64.yml",
"chars": 1618,
"preview": "name: Publish Docker image (arm64)\n\non:\n push:\n tags:\n - '*'\n - '!*-alpha*'\n workflow_dispatch:\n input"
},
{
"path": ".github/workflows/github-pages.yml",
"chars": 1067,
"preview": "name: Build GitHub Pages\non:\n workflow_dispatch:\n inputs:\n name:\n description: 'Reason'\n required"
},
{
"path": ".github/workflows/linux-release.yml",
"chars": 1312,
"preview": "name: Linux Release\npermissions:\n contents: write\n\non:\n push:\n tags:\n - '*'\n - '!*-alpha*'\njobs:\n releas"
},
{
"path": ".github/workflows/macos-release.yml",
"chars": 908,
"preview": "name: macOS Release\npermissions:\n contents: write\n\non:\n push:\n tags:\n - '*'\n - '!*-alpha*'\njobs:\n releas"
},
{
"path": ".github/workflows/windows-release.yml",
"chars": 958,
"preview": "name: Windows Release\npermissions:\n contents: write\n\non:\n push:\n tags:\n - '*'\n - '!*-alpha*'\njobs:\n rele"
},
{
"path": ".gitignore",
"chars": 37,
"preview": ".idea\n.vscode\nupload\n*.exe\n*.db\nbuild"
},
{
"path": "Dockerfile",
"chars": 546,
"preview": "# 使用 Golang 镜像作为构建阶段\nFROM golang AS builder\n\n# 设置环境变量\nENV GO111MODULE=on \\\n CGO_ENABLED=0 \\\n GOOS=linux\n\n# 设置工作目录\n"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 9403,
"preview": "<p align=\"right\">\n <strong>中文</strong> \n</p>\n<div align=\"center\">\n\n# Genspark2API\n\n_觉得有点意思的话 别忘了点个 ⭐_\n\n<a href=\"https:"
},
{
"path": "check/check.go",
"chars": 1973,
"preview": "package check\n\nimport (\n\t\"genspark2api/common\"\n\t\"genspark2api/common/config\"\n\tlogger \"genspark2api/common/loggger\"\n\t\"git"
},
{
"path": "common/config/config.go",
"chars": 9583,
"preview": "package config\n\nimport (\n\t\"errors\"\n\t\"genspark2api/common/env\"\n\t\"genspark2api/yescaptcha\"\n\t\"math/rand\"\n\t\"os\"\n\t\"strings\"\n\t"
},
{
"path": "common/constants.go",
"chars": 2703,
"preview": "package common\n\nimport \"time\"\n\nvar StartTime = time.Now().Unix() // unit: second\n\nvar Version = \"v1.12.6\" // this hard c"
},
{
"path": "common/env/helper.go",
"chars": 775,
"preview": "package env\n\nimport (\n\t\"os\"\n\t\"strconv\"\n)\n\nfunc Bool(env string, defaultValue bool) bool {\n\tif env == \"\" || os.Getenv(env"
},
{
"path": "common/helper/helper.go",
"chars": 2550,
"preview": "package helper\n\nimport (\n\t\"fmt\"\n\t\"genspark2api/common/random\"\n\t\"github.com/gin-gonic/gin\"\n\t\"html/template\"\n\t\"log\"\n\t\"net\""
},
{
"path": "common/helper/key.go",
"chars": 57,
"preview": "package helper\n\nconst (\n\tRequestIdKey = \"X-Request-Id\"\n)\n"
},
{
"path": "common/helper/time.go",
"chars": 229,
"preview": "package helper\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc GetTimestamp() int64 {\n\treturn time.Now().Unix()\n}\n\nfunc GetTimeString()"
},
{
"path": "common/init.go",
"chars": 1180,
"preview": "package common\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nvar (\n\tPort = flag.Int(\"port\", 7055, \"t"
},
{
"path": "common/loggger/constants.go",
"chars": 34,
"preview": "package logger\n\nvar LogDir string\n"
},
{
"path": "common/loggger/logger.go",
"chars": 2345,
"preview": "package logger\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"genspark2api/common/config\"\n\t\"genspark2api/common/helper\"\n\t\"io\"\n\t\"log\"\n\t\"os"
},
{
"path": "common/random/main.go",
"chars": 1272,
"preview": "package random\n\nimport (\n\t\"github.com/google/uuid\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc GetUUID() string {\n\tcode := u"
},
{
"path": "common/rate-limit.go",
"chars": 1489,
"preview": "package common\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\ntype InMemoryRateLimiter struct {\n\tstore map[string]*[]int64\n\tm"
},
{
"path": "common/token.go",
"chars": 6134,
"preview": "package common\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\tlogger \"genspark2api/common/loggger\"\n\t\"genspark2api/model\"\n\t\"github.com/pkouk"
},
{
"path": "common/utils.go",
"chars": 9683,
"preview": "package common\n\nimport (\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"github.com/google/uuid\"\n\tjsoniter \"github.com/json-iterator/go\"\n\t_ "
},
{
"path": "controller/api.go",
"chars": 233,
"preview": "package controller\n\nimport (\n\t\"github.com/deanxv/CycleTLS/cycletls\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n// ChatForOpenAI 处理Op"
},
{
"path": "controller/chat.go",
"chars": 57417,
"preview": "package controller\n\nimport (\n\t\"bufio\"\n\t\"crypto/tls\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"genspark2api/common\"\n\t\""
},
{
"path": "controller/video.go",
"chars": 14662,
"preview": "package controller\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"genspark2api/common\"\n\t\"genspark2"
},
{
"path": "docker-compose.yml",
"chars": 361,
"preview": "version: '3.4'\n\nservices:\n genspark2api:\n image: deanxv/genspark2api:latest\n container_name: genspark2api\n res"
},
{
"path": "go.mod",
"chars": 2105,
"preview": "module genspark2api\n\ngo 1.23.0\n\ntoolchain go1.23.2\n\nrequire (\n\tgithub.com/deanxv/CycleTLS/cycletls v0.0.0-20250208071223"
},
{
"path": "go.sum",
"chars": 45845,
"preview": "cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=\ncloud.google.com/go v0.31.0/go.mod h1"
},
{
"path": "job/cookie.go",
"chars": 754,
"preview": "package job\n\nimport (\n\t\"genspark2api/common/config\"\n\tlogger \"genspark2api/common/loggger\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc L"
},
{
"path": "main.go",
"chars": 1230,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"genspark2api/check\"\n\t\"genspark2api/common\"\n\t\"genspark2api/common/config\"\n\tlogger \"genspa"
},
{
"path": "middleware/auth.go",
"chars": 1256,
"preview": "package middleware\n\nimport (\n\t\"genspark2api/common/config\"\n\t\"genspark2api/model\"\n\t\"github.com/gin-gonic/gin\"\n\t\"github.co"
},
{
"path": "middleware/cors.go",
"chars": 355,
"preview": "package middleware\n\nimport (\n\t\"github.com/gin-contrib/cors\"\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc CORS() gin.HandlerFunc {"
},
{
"path": "middleware/ip-list.go",
"chars": 555,
"preview": "package middleware\n\nimport (\n\t\"genspark2api/common/config\"\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n\t\"strings\"\n)\n\n// IPBl"
},
{
"path": "middleware/logger.go",
"chars": 560,
"preview": "package middleware\n\nimport (\n\t\"fmt\"\n\t\"genspark2api/common/helper\"\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc SetUpLogger(server"
},
{
"path": "middleware/rate-limit.go",
"chars": 972,
"preview": "package middleware\n\nimport (\n\t\"genspark2api/common\"\n\t\"genspark2api/common/config\"\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http"
},
{
"path": "middleware/request-id.go",
"chars": 401,
"preview": "package middleware\n\nimport (\n\t\"context\"\n\t\"genspark2api/common/helper\"\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc RequestId() fu"
},
{
"path": "model/openai.go",
"chars": 6124,
"preview": "package model\n\nimport \"encoding/json\"\n\ntype OpenAIChatCompletionRequest struct {\n\tModel string `json:\"mo"
},
{
"path": "router/api-router.go",
"chars": 1140,
"preview": "package router\n\nimport (\n\t\"fmt\"\n\t\"genspark2api/common/config\"\n\t\"genspark2api/controller\"\n\t\"genspark2api/middleware\"\n\t\"gi"
},
{
"path": "router/main.go",
"chars": 117,
"preview": "package router\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc SetRouter(router *gin.Engine) {\n\tSetApiRouter(router)\n}\n"
},
{
"path": "yescaptcha/main.go",
"chars": 5123,
"preview": "package yescaptcha\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n)\n\nconst (\n"
}
]
About this extraction
This page contains the full source code of the deanxv/genspark2api GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 47 files (230.1 KB), approximately 79.0k tokens, and a symbol index with 222 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.