rename chatgpt microservice (#30)

* rename chagpt microservice

* add deprecated models
This commit is contained in:
Dmitry Afanasyev
2023-10-09 00:22:26 +03:00
committed by GitHub
parent 6a97c29023
commit f6f3865fb6
34 changed files with 14 additions and 4 deletions

View File

@@ -0,0 +1,101 @@
---
Language: Cpp
# BasedOnStyle: Google
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlinesLeft: true
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 119
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeCategories:
- Regex: '^<.*\.h>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: true
IndentWidth: 4
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 4
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: c++20
TabWidth: 8
UseTab: Never
...
---
Language: JavaScript
DisableFormat: true
---
Language: Json
DisableFormat: true

View File

@@ -0,0 +1,64 @@
name: build
on:
push:
branches: ["main", "dev"]
pull_request:
branches: ["main"]
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-22.04]
steps:
- name: Installation
run: |
sudo apt-get update
sudo apt-get install -y libgl1-mesa-dev libglu1-mesa-dev p7zip gobjc g++-13 wget sudo libcurl4-openssl-dev libnss3 nss-plugin-pem ca-certificates
wget https://github.com/lwthiker/curl-impersonate/releases/download/v0.5.4/libcurl-impersonate-v0.5.4.x86_64-linux-gnu.tar.gz
sudo mv libcurl-impersonate-v0.5.4.x86_64-linux-gnu.tar.gz /usr/lib64
cd /usr/lib64
sudo tar -xvf libcurl-impersonate-v0.5.4.x86_64-linux-gnu.tar.gz
cd -
wget https://github.com/xmake-io/xmake/releases/download/v2.8.2/xmake-v2.8.2.xz.run
chmod 777 xmake-v2.8.2.xz.run
./xmake-v2.8.2.xz.run > a.txt
- name: checkout
uses: actions/checkout@v3
- name: build
run: |
export XMAKE_ROOT="y"
source ~/.xmake/profile
g++-13 -v
export LD_LIBRARY_PATH=/usr/lib64:$LD_LIBRARY_PATH
export LIBRARY_PATH=/usr/lib64:$LIBRARY_PATH
export CXX=g++-13
export CC=gcc-13
xmake build -y
xmake install -o .
ldd ./bin/cpp-freegpt-webui
- name: Docker login
if: github.ref_name == 'dev' || github.ref_name == 'main'
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build the Docker image to main
if: github.ref_name == 'main'
run: |
docker build . -t ${{ secrets.DOCKERHUB_USERNAME }}/freegpt:latest
- name: Docker image push to dev
if: github.ref_name == 'dev'
run: docker push ${{ secrets.DOCKERHUB_USERNAME }}/freegpt:dev
- name: Docker image push main
if: github.ref_name == 'main'
run: docker push ${{ secrets.DOCKERHUB_USERNAME }}/freegpt:latest

157
chatgpt_microservice/.gitignore vendored Normal file
View File

@@ -0,0 +1,157 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# others
.config/
.upm/
.vscode/
# PyCharm
# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/

View File

@@ -0,0 +1,28 @@
FROM ubuntu:23.04
#use --build-arg LIB_DIR=/usr/lib for arm64 cpus
ARG LIB_DIR=/usr/lib64
ENV LD_LIBRARY_PATH=$LIB_DIR:$LD_LIBRARY_PATH
ENV LIBRARY_PATH=$LIB_DIR:$LIBRARY_PATH
RUN apt-get update -y
RUN apt-get install -y libcurl4-openssl-dev wget libnss3 nss-plugin-pem ca-certificates
# RUN strings /lib/$(arch)-linux-gnu/libstdc++.so.6 | grep GLIBCXX_3.4
RUN wget https://github.com/lwthiker/curl-impersonate/releases/download/v0.5.4/libcurl-impersonate-v0.5.4.$(arch)-linux-gnu.tar.gz
RUN mv libcurl-impersonate-v0.5.4.$(arch)-linux-gnu.tar.gz $LIB_DIR
RUN cd $LIB_DIR && tar -xvf libcurl-impersonate-v0.5.4.$(arch)-linux-gnu.tar.gz && rm -rf libcurl-impersonate-v0.5.4.$(arch)-linux-gnu.tar.gz
WORKDIR /app
ADD bin /app/bin
ADD cfg /app/cfg
ADD client /app/client
RUN ls /app/bin
RUN ls /app/cfg
WORKDIR /app/bin
ENTRYPOINT ["sh", "-c", "./cpp-freegpt-webui ../cfg/cpp-free-gpt.yml"]

View File

@@ -0,0 +1,674 @@
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>.

View File

@@ -0,0 +1,122 @@
# Cpp FreeGPT WebUI
## GPT 3.5/4
<strong>NOT REQUIRE ANY API KEY</strong> ❌🔑
This project features a WebUI utilizing the [G4F API](https://github.com/xtekky/gpt4free). <br>
Experience the power of ChatGPT with a user-friendly interface, enhanced jailbreaks, and completely free.
## Getting Started :white_check_mark:
To get started with this project, you'll need to clone the repository and have g++ >= 13.1 installed on your system.
### Cloning the Repository :inbox_tray:
Run the following command to clone the repository:
```
git clone https://github.com/fantasy-peak/cpp-freegpt-webui.git
```
## Compile And Running the Application :rocket:
To run the application, run the following command:
```
1. Check local g++ version, need g++ version >= gcc version 13.1.0 (GCC)
2. install xmake
wget https://github.com/xmake-io/xmake/releases/download/v2.8.2/xmake-v2.8.2.xz.run
chmod 777 xmake-v2.8.2.xz.run
./xmake-v2.8.2.xz.run
source ~/.xmake/profile
3. install libcurl-impersonate, ubuntu (apt-get install libcurl4-openssl-dev) centos7 (yum install libcurl-devel.x86_64)
wget https://github.com/lwthiker/curl-impersonate/releases/download/v0.5.4/libcurl-impersonate-v0.5.4.x86_64-linux-gnu.tar.gz
sudo mv libcurl-impersonate-v0.5.4.x86_64-linux-gnu.tar.gz /usr/lib64
cd /usr/lib64
sudo tar -xvf libcurl-impersonate-v0.5.4.x86_64-linux-gnu.tar.gz
export LD_LIBRARY_PATH=/usr/lib64:$LD_LIBRARY_PATH
export LIBRARY_PATH=/usr/lib64:$LIBRARY_PATH
4. Compiling
git clone https://github.com/fantasy-peak/cpp-freegpt-webui.git
cd cpp-freegpt-webui
xmake build -v -y
xmake install -o .
cd bin
./cpp-freegpt-webui ../cfg/cpp-free-gpt.yml
```
Access the application in your browser using the URL:
```
http://127.0.0.1:8858/chat
```
### Running the Docker
Pull the Docker image from Docker Hub:
```
docker pull fantasypeak/freegpt:latest
```
Run the application using Docker:
```
docker run -p 8858:8858 -it --name freegpt fantasypeak/freegpt:latest
// OR
docker run --net=host -it --name freegpt fantasypeak/freegpt:latest
// use http_proxy
docker run -p 8858:8858 -it --name freegpt -e HTTP_PROXY=http://127.0.0.1:8080 -e CHAT_PATH=/chat fantasypeak/freegpt:latest
// set active providers
docker run -p 8858:8858 -it --name freegpt -e CHAT_PATH=/chat -e PROVIDERS="[\"gpt-4-ChatgptAi\",\"gpt-3.5-turbo-stream-DeepAi\"]" fantasypeak/freegpt:latest
// enable ip white list function
docker run -p 8858:8858 -it --name freegpt -e IP_WHITE_LIST="[\"127.0.0.1\",\"192.168.1.1\"]" fantasypeak/freegpt:latest
```
### Call OpenAi Api
```
// It supports calling OpenAI's API, but need set API_KEY
docker run -p 8858:8858 -it --name freegpt -e CHAT_PATH=/chat -e API_KEY=a40f22f2-c1a2-4b1d-a47f-55ae1a7ddbed fantasypeak/freegpt:latest
```
### WebUI
The application interface was incorporated from the [chatgpt-clone](https://github.com/xtekky/chatgpt-clone) repository.
<img src='chat.png'>
### API G4F
The free GPT-4 API was incorporated from the [GPT4Free](https://github.com/xtekky/gpt4free) repository.
## Legal Notice
This repository is _not_ associated with or endorsed by providers of the APIs contained in this GitHub repository. This
project is intended **for educational purposes only**. This is just a little personal project. Sites may contact me to
improve their security or request the removal of their site from this repository.
Please note the following:
1. **Disclaimer**: The APIs, services, and trademarks mentioned in this repository belong to their respective owners.
This project is _not_ claiming any right over them nor is it affiliated with or endorsed by any of the providers
mentioned.
2. **Responsibility**: The author of this repository is _not_ responsible for any consequences, damages, or losses
arising from the use or misuse of this repository or the content provided by the third-party APIs. Users are solely
responsible for their actions and any repercussions that may follow. We strongly recommend the users to follow the
TOS of the each Website.
3. **Educational Purposes Only**: This repository and its content are provided strictly for educational purposes. By
using the information and code provided, users acknowledge that they are using the APIs and models at their own risk
and agree to comply with any applicable laws and regulations.
4. **Copyright**: All content in this repository, including but not limited to code, images, and documentation, is the
intellectual property of the repository author, unless otherwise stated. Unauthorized copying, distribution, or use
of any content in this repository is strictly prohibited without the express written consent of the repository
author.
5. **Indemnification**: Users agree to indemnify, defend, and hold harmless the author of this repository from and
against any and all claims, liabilities, damages, losses, or expenses, including legal fees and costs, arising out of
or in any way connected with their use or misuse of this repository, its content, or related third-party APIs.
6. **Updates and Changes**: The author reserves the right to modify, update, or remove any content, information, or
features in this repository at any time without prior notice. Users are responsible for regularly reviewing the
content and any changes made to this repository.
By using this repository or any code related to it, you agree to these terms. The author is not responsible for any
copies, forks, or reuploads made by other users. This is the author's only account and repository. To prevent
impersonation or irresponsible actions, you may comply with the GNU GPL license this Repository uses.

View File

@@ -0,0 +1,5 @@
---
client_root_path: "../client"
enable_proxy: true
providers: []
ip_white_list: []

Binary file not shown.

After

Width:  |  Height:  |  Size: 239 KiB

View File

@@ -0,0 +1,821 @@
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap");
/* :root {
--colour-1: #ffffff;
--colour-2: #000000;
--colour-3: #000000;
--colour-4: #000000;
--colour-5: #000000;
--colour-6: #000000;
--accent: #ffffff;
--blur-bg: #98989866;
--blur-border: #00000040;
--user-input: #000000;
--conversations: #000000;
} */
:root {
--colour-1: #000000;
--colour-2: #ccc;
--colour-3: #e4d4ff;
--colour-4: #f0f0f0;
--colour-5: #181818;
--colour-6: #242424;
--accent: #8b3dff;
--blur-bg: #16101b66;
--blur-border: #84719040;
--user-input: #ac87bb;
--conversations: #c7a2ff;
}
:root {
--font-1: "Inter", sans-serif;
--section-gap: 25px;
--border-radius-1: 8px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
position: relative;
font-family: var(--font-1);
}
html,
body {
scroll-behavior: smooth;
overflow: hidden;
}
body {
padding: var(--section-gap);
background: var(--colour-1);
color: var(--colour-3);
min-height: 100vh;
}
.row {
display: flex;
gap: var(--section-gap);
height: 100%;
}
.box {
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
background-color: var(--blur-bg);
height: 100%;
width: 100%;
border-radius: var(--border-radius-1);
border: 1px solid var(--blur-border);
}
.conversations {
max-width: 260px;
padding: var(--section-gap);
overflow: auto;
flex-shrink: 0;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.conversation {
width: 100%;
min-height: 50%;
height: 100vh;
overflow-y: scroll;
overflow-x: hidden;
display: flex;
flex-direction: column;
gap: 15px;
}
.conversation #messages {
width: 100%;
display: flex;
flex-direction: column;
overflow-wrap: break-word;
overflow-y: inherit;
overflow-x: hidden;
padding-bottom: 50px;
}
.conversation .user-input {
max-height: 10vh;
}
.conversation .user-input input {
font-size: 15px;
width: 100%;
height: 100%;
padding: 12px 15px;
background: none;
border: none;
outline: none;
color: var(--colour-3);
}
.conversation .user-input input::placeholder {
color: var(--user-input)
}
.gradient:nth-child(1) {
--top: 0;
--right: 0;
--size: 70vw;
--blur: calc(0.5 * var(--size));
--opacity: 0.3;
animation: zoom_gradient 6s infinite;
}
.gradient {
position: absolute;
z-index: -1;
border-radius: calc(0.5 * var(--size));
background-color: var(--accent);
background: radial-gradient(circle at center, var(--accent), var(--accent));
width: 70vw;
height: 70vw;
top: 50%;
right: 0;
transform: translateY(-50%);
filter: blur(calc(0.5 * 70vw)) opacity(var(--opacity));
}
.conversations {
display: flex;
flex-direction: column;
gap: 16px;
flex: auto;
min-width: 0;
}
.conversations .title {
font-size: 14px;
font-weight: 500;
}
.conversations .convo {
padding: 8px 12px;
display: flex;
gap: 18px;
align-items: center;
user-select: none;
justify-content: space-between;
}
.conversations .convo .left {
cursor: pointer;
display: flex;
align-items: center;
gap: 10px;
flex: auto;
min-width: 0;
}
.conversations i {
color: var(--conversations);
cursor: pointer;
}
.convo-title {
color: var(--colour-3);
font-size: 14px;
overflow: hidden;
text-overflow: ellipsis;
}
.message {
width: 100%;
overflow-wrap: break-word;
display: flex;
gap: var(--section-gap);
padding: var(--section-gap);
padding-bottom: 0;
}
.message:last-child {
animation: 0.6s show_message;
}
@keyframes show_message {
from {
transform: translateY(10px);
opacity: 0;
}
}
.message .user {
max-width: 48px;
max-height: 48px;
flex-shrink: 0;
}
.message .user img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 8px;
outline: 1px solid var(--blur-border);
}
.message .user:after {
content: "63";
position: absolute;
bottom: 0;
right: 0;
height: 60%;
width: 60%;
background: var(--colour-3);
filter: blur(10px) opacity(0.5);
z-index: 10000;
}
.message .content {
display: flex;
flex-direction: column;
gap: 18px;
min-width: 0;
}
.message .content p,
.message .content li,
.message .content code {
font-size: 15px;
line-height: 1.3;
}
.message .user i {
position: absolute;
bottom: -6px;
right: -6px;
z-index: 1000;
}
.new_convo {
padding: 8px 12px;
display: flex;
gap: 18px;
align-items: center;
cursor: pointer;
user-select: none;
background: transparent;
border: 1px dashed var(--conversations);
border-radius: var(--border-radius-1);
}
.new_convo span {
color: var(--colour-3);
font-size: 14px;
}
.new_convo:hover {
border-style: solid;
}
.stop_generating {
position: absolute;
bottom: 118px;
/* left: 10px;
bottom: 125px;
right: 8px; */
left: 50%;
transform: translateX(-50%);
z-index: 1000000;
}
.stop_generating button {
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
background-color: var(--blur-bg);
border-radius: var(--border-radius-1);
border: 1px solid var(--blur-border);
padding: 10px 15px;
color: var(--colour-3);
display: flex;
justify-content: center;
align-items: center;
gap: 12px;
cursor: pointer;
animation: show_popup 0.4s;
}
@keyframes show_popup {
from {
opacity: 0;
transform: translateY(10px);
}
}
@keyframes hide_popup {
to {
opacity: 0;
transform: translateY(10px);
}
}
.stop_generating-hiding button {
animation: hide_popup 0.4s;
}
.stop_generating-hidden button {
display: none;
}
.typing {
position: absolute;
top: -25px;
left: 0;
font-size: 14px;
animation: show_popup 0.4s;
}
.typing-hiding {
animation: hide_popup 0.4s;
}
.typing-hidden {
display: none;
}
input[type="checkbox"] {
height: 0;
width: 0;
display: none;
}
label {
cursor: pointer;
text-indent: -9999px;
width: 50px;
height: 30px;
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
background-color: var(--blur-bg);
border-radius: var(--border-radius-1);
border: 1px solid var(--blur-border);
display: block;
border-radius: 100px;
position: relative;
overflow: hidden;
transition: 0.33s;
}
label:after {
content: "";
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 5px;
width: 20px;
height: 20px;
background: var(--colour-3);
border-radius: 90px;
transition: 0.33s;
}
input:checked+label {
background: var(--blur-border);
}
input:checked+label:after {
left: calc(100% - 5px - 20px);
}
.buttons {
min-height: 10vh;
display: flex;
align-items: start;
justify-content: left;
width: 100%;
}
.field {
height: fit-content;
display: flex;
align-items: center;
gap: 16px;
padding-right: 15px
}
.field .about {
font-size: 14px;
color: var(--colour-3);
}
.disable-scrollbars::-webkit-scrollbar {
background: transparent; /* Chrome/Safari/Webkit */
width: 0px;
}
.disable-scrollbars {
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE 10+ */
}
select {
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
-webkit-backdrop-filter: blur(20px);
backdrop-filter: blur(20px);
cursor: pointer;
background-color: var(--blur-bg);
border: 1px solid var(--blur-border);
color: var(--colour-3);
display: block;
position: relative;
overflow: hidden;
outline: none;
padding: 8px 16px;
appearance: none;
}
.input-box {
display: flex;
align-items: center;
padding-right: 15px;
cursor: pointer;
}
.info {
padding: 8px 12px;
display: flex;
gap: 18px;
align-items: center;
user-select: none;
background: transparent;
border-radius: var(--border-radius-1);
width: 100%;
cursor: default;
border: 1px dashed var(--conversations)
}
.bottom_buttons {
width: 100%;
display: flex;
flex-direction: column;
gap: 10px;
}
.bottom_buttons button {
padding: 8px 12px;
display: flex;
gap: 18px;
align-items: center;
cursor: pointer;
user-select: none;
background: transparent;
border: 1px solid #c7a2ff;
border-radius: var(--border-radius-1);
width: 100%;
}
.bottom_buttons button span {
color: var(--colour-3);
font-size: 14px;
}
.conversations .top {
display: flex;
flex-direction: column;
gap: 16px;
overflow: auto;
}
#cursor {
line-height: 17px;
margin-left: 3px;
-webkit-animation: blink 0.8s infinite;
animation: blink 0.8s infinite;
width: 7px;
height: 15px;
}
@keyframes blink {
0% {
background: #ffffff00;
}
50% {
background: white;
}
100% {
background: #ffffff00;
}
}
@-webkit-keyframes blink {
0% {
background: #ffffff00;
}
50% {
background: white;
}
100% {
background: #ffffff00;
}
}
ol,
ul {
padding-left: 20px;
}
@keyframes spinner {
to {
transform: rotate(360deg);
}
}
.spinner:before {
content: '';
box-sizing: border-box;
position: absolute;
top: 50%;
left: 45%;
width: 20px;
height: 20px;
border-radius: 50%;
border: 1px solid var(--conversations);
border-top-color: white;
animation: spinner .6s linear infinite;
}
.grecaptcha-badge {
visibility: hidden;
}
.mobile-sidebar {
display: none !important;
position: absolute;
z-index: 100000;
top: 0;
left: 0;
margin: 10px;
font-size: 20px;
cursor: pointer;
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
background-color: var(--blur-bg);
border-radius: 10px;
border: 1px solid var(--blur-border);
width: 40px;
height: 40px;
justify-content: center;
align-items: center;
transition: 0.33s;
}
.mobile-sidebar i {
transition: 0.33s;
}
.rotated {
transform: rotate(360deg);
}
@media screen and (max-width: 990px) {
.conversations {
display: none;
width: 100%;
max-width: none;
}
.buttons {
flex-wrap: wrap;
gap: 5px;
padding-bottom: 10vh;
margin-bottom: 10vh;
}
.field {
min-height: 5%;
width: fit-content;
}
.mobile-sidebar {
display: flex !important;
}
}
@media screen and (max-height: 640px) {
body {
height: 87vh
}
}
.shown {
display: flex;
}
a:-webkit-any-link {
color: var(--accent);
}
.conversation .user-input textarea {
font-size: 15px;
width: 100%;
height: 100%;
padding: 12px 15px;
background: none;
border: none;
outline: none;
color: var(--colour-3);
resize: vertical;
max-height: 150px;
min-height: 80px;
}
/* style for hljs copy */
.hljs-copy-wrapper {
position: relative;
overflow: hidden
}
.hljs-copy-wrapper:hover .hljs-copy-button,
.hljs-copy-button:focus {
transform: translateX(0)
}
.hljs-copy-button {
position: absolute;
transform: translateX(calc(100% + 1.125em));
top: 1em;
right: 1em;
width: 2rem;
height: 2rem;
text-indent: -9999px;
color: #fff;
border-radius: .25rem;
border: 1px solid #ffffff22;
background-color: #2d2b57;
background-image: url('data:image/svg+xml;utf-8,<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M6 5C5.73478 5 5.48043 5.10536 5.29289 5.29289C5.10536 5.48043 5 5.73478 5 6V20C5 20.2652 5.10536 20.5196 5.29289 20.7071C5.48043 20.8946 5.73478 21 6 21H18C18.2652 21 18.5196 20.8946 18.7071 20.7071C18.8946 20.5196 19 20.2652 19 20V6C19 5.73478 18.8946 5.48043 18.7071 5.29289C18.5196 5.10536 18.2652 5 18 5H16C15.4477 5 15 4.55228 15 4C15 3.44772 15.4477 3 16 3H18C18.7956 3 19.5587 3.31607 20.1213 3.87868C20.6839 4.44129 21 5.20435 21 6V20C21 20.7957 20.6839 21.5587 20.1213 22.1213C19.5587 22.6839 18.7957 23 18 23H6C5.20435 23 4.44129 22.6839 3.87868 22.1213C3.31607 21.5587 3 20.7957 3 20V6C3 5.20435 3.31607 4.44129 3.87868 3.87868C4.44129 3.31607 5.20435 3 6 3H8C8.55228 3 9 3.44772 9 4C9 4.55228 8.55228 5 8 5H6Z" fill="white"/><path fill-rule="evenodd" clip-rule="evenodd" d="M7 3C7 1.89543 7.89543 1 9 1H15C16.1046 1 17 1.89543 17 3V5C17 6.10457 16.1046 7 15 7H9C7.89543 7 7 6.10457 7 5V3ZM15 3H9V5H15V3Z" fill="white"/></svg>');
background-repeat: no-repeat;
background-position: center;
transition: background-color 200ms ease, transform 200ms ease-out
}
.hljs-copy-button:hover {
border-color: #ffffff44
}
.hljs-copy-button:active {
border-color: #ffffff66
}
.hljs-copy-button[data-copied="true"] {
text-indent: 0;
width: auto;
background-image: none
}
@media(prefers-reduced-motion) {
.hljs-copy-button {
transition: none
}
}
.hljs-copy-alert {
clip: rect(0 0 0 0);
clip-path: inset(50%);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px
}
.visually-hidden {
clip: rect(0 0 0 0);
clip-path: inset(50%);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}
.color-picker>fieldset {
border: 0;
display: flex;
width: fit-content;
background: var(--colour-1);
margin-inline: auto;
border-radius: 8px;
-webkit-backdrop-filter: blur(20px);
backdrop-filter: blur(20px);
cursor: pointer;
background-color: var(--blur-bg);
border: 1px solid var(--blur-border);
color: var(--colour-3);
display: block;
position: relative;
overflow: hidden;
outline: none;
padding: 6px 16px;
}
.color-picker input[type="radio"]:checked {
background-color: var(--radio-color);
}
.color-picker input[type="radio"]#light {
--radio-color: gray;
}
.color-picker input[type="radio"]#pink {
--radio-color: pink;
}
.color-picker input[type="radio"]#blue {
--radio-color: blue;
}
.color-picker input[type="radio"]#green {
--radio-color: green;
}
.color-picker input[type="radio"]#dark {
--radio-color: #232323;
}
.pink {
--colour-1: hsl(310 50% 90%);
--clr-card-bg: hsl(310 50% 100%);
--colour-3: hsl(310 50% 15%);
--conversations: hsl(310 50% 25%);
}
.blue {
--colour-1: hsl(209 50% 90%);
--clr-card-bg: hsl(209 50% 100%);
--colour-3: hsl(209 50% 15%);
--conversations: hsl(209 50% 25%);
}
.green {
--colour-1: hsl(109 50% 90%);
--clr-card-bg: hsl(109 50% 100%);
--colour-3: hsl(109 50% 15%);
--conversations: hsl(109 50% 25%);
}
.dark {
--colour-1: hsl(209 50% 10%);
--clr-card-bg: hsl(209 50% 5%);
--colour-3: hsl(209 50% 90%);
--conversations: hsl(209 50% 80%);
}
:root:has(#pink:checked) {
--colour-1: hsl(310 50% 90%);
--clr-card-bg: hsl(310 50% 100%);
--colour-3: hsl(310 50% 15%);
--conversations: hsl(310 50% 25%);
}
:root:has(#blue:checked) {
--colour-1: hsl(209 50% 90%);
--clr-card-bg: hsl(209 50% 100%);
--colour-3: hsl(209 50% 15%);
--conversations: hsl(209 50% 25%);
}
:root:has(#green:checked) {
--colour-1: hsl(109 50% 90%);
--clr-card-bg: hsl(109 50% 100%);
--colour-3: hsl(109 50% 15%);
--conversations: hsl(109 50% 25%);
}
:root:has(#dark:checked) {
--colour-1: hsl(209 50% 10%);
--clr-card-bg: hsl(209 50% 5%);
--colour-3: hsl(209 50% 90%);
--conversations: hsl(209 50% 80%);
}
.trash-icon {
position: absolute;
top: 20px;
right: 20px;
}

View File

@@ -0,0 +1,155 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=1.0">
<meta name="description" content="A conversational AI system that listens, learns, and challenges">
<meta property="og:title" content="ChatGPT">
<meta property="og:image" content="https://openai.com/content/images/2022/11/ChatGPT.jpg">
<meta property="og:description" content="A conversational AI system that listens, learns, and challenges">
<meta property="og:url" content="https://chat.acy.dev">
<link rel="stylesheet" href="{{chat_path}}/assets/css/style.css">
<link rel="apple-touch-icon" sizes="180x180" href="{{chat_path}}/assets/img/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="{{chat_path}}/assets/img/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="{{chat_path}}/assets/img/favicon-16x16.png">
<link rel="manifest" href="{{chat_path}}/assets/img/site.webmanifest">
<script src="{{chat_path}}/assets/js/icons.js"></script>
<script src="{{chat_path}}/assets/js/chat.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/markdown-it@latest/dist/markdown-it.min.js"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@latest/build/styles/base16/dracula.min.css">
<script>
const user_image = `<img src="{{chat_path}}/assets/img/user.png" alt="User Avatar">`;
const gpt_image = `<img src="{{chat_path}}/assets/img/gpt.png" alt="GPT Avatar">`;
</script>
<style>
.hljs {
color: #e9e9f4;
background: #28293629;
border-radius: var(--border-radius-1);
border: 1px solid var(--blur-border);
font-size: 15px;
}
#message-input {
margin-right: 30px;
height: 80px;
}
#message-input::-webkit-scrollbar {
width: 5px;
}
/* Track */
#message-input::-webkit-scrollbar-track {
background: #f1f1f1;
}
/* Handle */
#message-input::-webkit-scrollbar-thumb {
background: #c7a2ff;
}
/* Handle on hover */
#message-input::-webkit-scrollbar-thumb:hover {
background: #8b3dff;
}
</style>
<script src="{{chat_path}}/assets/js/highlight.min.js"></script>
<script src="{{chat_path}}/assets/js/highlightjs-copy.min.js"></script>
<script>window.conversation_id = {{chat_id}} </script>
<title>ChatGPT</title>
</head>
<body>
<div class="gradient"></div>
<div class="row">
<div class="box conversations">
<div class="top">
<button class="new_convo" onclick="new_conversation()">
<i class="fa-regular fa-plus"></i>
<span>New Conversation</span>
</button>
<div class="spinner"></div>
</div>
<div class="bottom_buttons">
<button onclick="delete_conversations()">
<i class="fa-regular fa-trash"></i>
<span>Clear Conversations</span>
</button>
<div class="info">
<i class="fa-regular fa-circle-info"></i>
<span class="convo-title">By: Balsh<br>
Version: 0.0.7 <br>
Release: 2023-09-28<br>
</span>
</div>
</div>
</div>
<div class="conversation disable-scrollbars">
<div class="stop_generating stop_generating-hidden">
<button id="cancelButton">
<span>Stop Generating</span>
<i class="fa-regular fa-stop"></i>
</button>
</div>
<div class="box" id="messages">
</div>
<div class="user-input">
<div class="box input-box">
<textarea id="message-input" placeholder="Ask a question" cols="30" rows="10" style="white-space: pre-wrap;" oninput="resizeTextarea(this)"></textarea>
<div id="send-button">
<i class="fa-regular fa-paper-plane-top"></i>
</div>
</div>
</div>
<div class="buttons">
<div class="field">
<input type="checkbox" id="switch"/>
<label for="switch"></label>
<span class="about">Web Access</span>
</div>
<div class="field">
<select name="model" id="model">
## for m in model_list
{% if loop.index1 == 1 %}
<option value="{{ m }}" selected>{{ m }}</option>
{% else %}
<option value="{{ m }}">{{ m }}</option>
{% endif %}
## endfor
</select>
<!-- <span class="about">Model</span> -->
</div>
<div class="field">
<select name="jailbreak" id="jailbreak">
<option value="default" selected>default</option>
</select>
</div>
<form class="color-picker" action="">
<fieldset>
<legend class="visually-hidden">Pick a color scheme</legend>
<label for="light" class="visually-hidden">Light</label>
<input type="radio" title="light" name="theme" id="light" checked>
<label for="pink" class="visually-hidden">Pink theme</label>
<input type="radio" title="pink" id="pink" name="theme">
<label for="blue" class="visually-hidden">Blue theme</label>
<input type="radio" title="blue" id="blue" name="theme">
<label for="green" class="visually-hidden">Green theme</label>
<input type="radio" title="green" id="green" name="theme">
<label for="dark" class="visually-hidden">Dark theme</label>
<input type="radio" title="dark" id="dark" name="theme">
</fieldset>
</form>
</div>
</div>
</div>
<div class="mobile-sidebar">
<i class="fa-solid fa-bars"></i>
</div>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 499 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

@@ -0,0 +1,19 @@
{
"name": "",
"short_name": "",
"icons": [
{
"src": "{{chat_path}}/assets/img/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "{{chat_path}}/assets/img/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,599 @@
const query = (obj) =>
Object.keys(obj)
.map((k) => encodeURIComponent(k) + "=" + encodeURIComponent(obj[k]))
.join("&");
const colorThemes = document.querySelectorAll('[name="theme"]');
const markdown = window.markdownit();
const message_box = document.getElementById(`messages`);
const message_input = document.getElementById(`message-input`);
const box_conversations = document.querySelector(`.top`);
const spinner = box_conversations.querySelector(".spinner");
const stop_generating = document.querySelector(`.stop_generating`);
const send_button = document.querySelector(`#send-button`);
let prompt_lock = false;
hljs.addPlugin(new CopyButtonPlugin());
function resizeTextarea(textarea) {
textarea.style.height = '80px';
textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
}
const format = (text) => {
return text.replace(/(?:\r\n|\r|\n)/g, "<br>");
};
message_input.addEventListener("blur", () => {
window.scrollTo(0, 0);
});
message_input.addEventListener("focus", () => {
document.documentElement.scrollTop = document.documentElement.scrollHeight;
});
const delete_conversations = async () => {
localStorage.clear();
await new_conversation();
};
const handle_ask = async () => {
message_input.style.height = `80px`;
message_input.focus();
window.scrollTo(0, 0);
let message = message_input.value;
if (message.length > 0) {
message_input.value = ``;
await ask_gpt(message);
}
};
const remove_cancel_button = async () => {
stop_generating.classList.add(`stop_generating-hiding`);
setTimeout(() => {
stop_generating.classList.remove(`stop_generating-hiding`);
stop_generating.classList.add(`stop_generating-hidden`);
}, 300);
};
const ask_gpt = async (message) => {
try {
message_input.value = ``;
message_input.innerHTML = ``;
message_input.innerText = ``;
add_conversation(window.conversation_id, message.substr(0, 20));
window.scrollTo(0, 0);
window.controller = new AbortController();
jailbreak = document.getElementById("jailbreak");
model = document.getElementById("model");
prompt_lock = true;
window.text = ``;
window.token = message_id();
stop_generating.classList.remove(`stop_generating-hidden`);
message_box.innerHTML += `
<div class="message">
<div class="user">
${user_image}
<i class="fa-regular fa-phone-arrow-up-right"></i>
</div>
<div class="content" id="user_${token}">
${format(message)}
</div>
<i class="fa fa-trash trash-icon" onclick="deleteMessage('${token}')"></i>
</div>
`;
/* .replace(/(?:\r\n|\r|\n)/g, '<br>') */
message_box.scrollTop = message_box.scrollHeight;
window.scrollTo(0, 0);
await new Promise((r) => setTimeout(r, 500));
window.scrollTo(0, 0);
message_box.innerHTML += `
<div class="message">
<div class="user">
${gpt_image} <i class="fa-regular fa-phone-arrow-down-left"></i>
</div>
<div class="content" id="gpt_${window.token}">
<div id="cursor"></div>
</div>
</div>
`;
message_box.scrollTop = message_box.scrollHeight;
window.scrollTo(0, 0);
await new Promise((r) => setTimeout(r, 1000));
window.scrollTo(0, 0);
const response = await fetch(`/backend-api/v2/conversation`, {
method: `POST`,
signal: window.controller.signal,
headers: {
"content-type": `application/json`,
accept: `text/event-stream`,
},
body: JSON.stringify({
conversation_id: window.conversation_id,
action: `_ask`,
model: model.options[model.selectedIndex].value,
jailbreak: jailbreak.options[jailbreak.selectedIndex].value,
meta: {
id: window.token,
content: {
conversation: await get_conversation(window.conversation_id),
internet_access: document.getElementById("switch").checked,
content_type: "text",
parts: [
{
content: message,
role: "user",
},
],
},
},
}),
});
const reader = response.body.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
chunk = new TextDecoder().decode(value);
if (
chunk.includes(
`<form id="challenge-form" action="/backend-api/v2/conversation?`
)
) {
chunk = `cloudflare token expired, please refresh the page.`;
}
text += chunk;
// const objects = chunk.match(/({.+?})/g);
// try { if (JSON.parse(objects[0]).success === false) throw new Error(JSON.parse(objects[0]).error) } catch (e) {}
// objects.forEach((object) => {
// console.log(object)
// try { text += h2a(JSON.parse(object).content) } catch(t) { console.log(t); throw new Error(t)}
// });
document.getElementById(`gpt_${window.token}`).innerHTML =
markdown.render(text);
document.querySelectorAll(`code`).forEach((el) => {
hljs.highlightElement(el);
});
window.scrollTo(0, 0);
message_box.scrollTo({ top: message_box.scrollHeight, behavior: "auto" });
}
// if text contains :
if (
text.includes(
`instead. Maintaining this website and API costs a lot of money`
)
) {
document.getElementById(`gpt_${window.token}`).innerHTML =
"An error occured, please reload / refresh cache and try again.";
}
add_message(window.conversation_id, "user", message, token);
add_message(window.conversation_id, "assistant", text, token);
message_box.scrollTop = message_box.scrollHeight;
await remove_cancel_button();
prompt_lock = false;
await load_conversations(20, 0);
window.scrollTo(0, 0);
} catch (e) {
add_message(window.conversation_id, "user", message, token);
message_box.scrollTop = message_box.scrollHeight;
await remove_cancel_button();
prompt_lock = false;
await load_conversations(20, 0);
console.log(e);
let cursorDiv = document.getElementById(`cursor`);
if (cursorDiv) cursorDiv.parentNode.removeChild(cursorDiv);
if (e.name != `AbortError`) {
let error_message = `oops ! something went wrong, please try again / reload. [stacktrace in console]`;
document.getElementById(`gpt_${window.token}`).innerHTML = error_message;
add_message(window.conversation_id, "assistant", error_message, token);
} else {
document.getElementById(`gpt_${window.token}`).innerHTML += ` [aborted]`;
add_message(window.conversation_id, "assistant", text + ` [aborted]`, token);
}
window.scrollTo(0, 0);
}
};
const clear_conversations = async () => {
const elements = box_conversations.childNodes;
let index = elements.length;
if (index > 0) {
while (index--) {
const element = elements[index];
if (
element.nodeType === Node.ELEMENT_NODE &&
element.tagName.toLowerCase() !== `button`
) {
box_conversations.removeChild(element);
}
}
}
};
const clear_conversation = async () => {
let messages = message_box.getElementsByTagName(`div`);
while (messages.length > 0) {
message_box.removeChild(messages[0]);
}
};
const show_option = async (conversation_id) => {
const conv = document.getElementById(`conv-${conversation_id}`);
const yes = document.getElementById(`yes-${conversation_id}`);
const not = document.getElementById(`not-${conversation_id}`);
conv.style.display = "none";
yes.style.display = "block";
not.style.display = "block";
}
const hide_option = async (conversation_id) => {
const conv = document.getElementById(`conv-${conversation_id}`);
const yes = document.getElementById(`yes-${conversation_id}`);
const not = document.getElementById(`not-${conversation_id}`);
conv.style.display = "block";
yes.style.display = "none";
not.style.display = "none";
}
const delete_conversation = async (conversation_id) => {
localStorage.removeItem(`conversation:${conversation_id}`);
const conversation = document.getElementById(`convo-${conversation_id}`);
conversation.remove();
if (window.conversation_id == conversation_id) {
await new_conversation();
}
await load_conversations(20, 0, true);
};
const set_conversation = async (conversation_id) => {
history.pushState({}, null, `{{chat_path}}/${conversation_id}`);
window.conversation_id = conversation_id;
await clear_conversation();
await load_conversation(conversation_id);
await load_conversations(20, 0, true);
};
const new_conversation = async () => {
history.pushState({}, null, `{{chat_path}}/`);
window.conversation_id = uuid();
await clear_conversation();
await load_conversations(20, 0, true);
};
const load_conversation = async (conversation_id) => {
let conversation = await JSON.parse(
localStorage.getItem(`conversation:${conversation_id}`)
);
console.log(conversation, conversation_id);
for (item of conversation.items) {
message_box.innerHTML += `
<div class="message">
<div class="user">
${item.role == "assistant" ? gpt_image : user_image}
${
item.role == "assistant"
? `<i class="fa-regular fa-phone-arrow-down-left"></i>`
: `<i class="fa-regular fa-phone-arrow-up-right"></i>`
}
</div>
${
item.role == "user"
? `<div class="content" id="user_${item.token}">`
: `<div class="content" id="gpt_${item.token}">`
}
${
item.role == "assistant"
? markdown.render(item.content)
: item.content
}
</div>
${
item.role == "user"
? `<i class="fa fa-trash trash-icon" onclick="deleteMessage('${item.token}')"></i>`
: ''
}
</div>
`;
}
document.querySelectorAll(`code`).forEach((el) => {
hljs.highlightElement(el);
});
message_box.scrollTo({ top: message_box.scrollHeight, behavior: "smooth" });
setTimeout(() => {
message_box.scrollTop = message_box.scrollHeight;
}, 500);
};
const get_conversation = async (conversation_id) => {
let conversation = await JSON.parse(
localStorage.getItem(`conversation:${conversation_id}`)
);
let result = conversation.items.slice(-4)
for (var i = 0; i < result.length; i++) {
delete result[i].token;
console.log(result[i]);
console.log(result[i]);
}
return result;
};
const add_conversation = async (conversation_id, title) => {
if (localStorage.getItem(`conversation:${conversation_id}`) == null) {
localStorage.setItem(
`conversation:${conversation_id}`,
JSON.stringify({
id: conversation_id,
title: title,
items: [],
})
);
}
};
const add_message = async (conversation_id, role, content, token) => {
before_adding = JSON.parse(
localStorage.getItem(`conversation:${conversation_id}`)
);
before_adding.items.push({
role: role,
content: content,
token: token,
});
localStorage.setItem(
`conversation:${conversation_id}`,
JSON.stringify(before_adding)
); // update conversation
};
const load_conversations = async (limit, offset, loader) => {
//console.log(loader);
//if (loader === undefined) box_conversations.appendChild(spinner);
let conversations = [];
for (let i = 0; i < localStorage.length; i++) {
if (localStorage.key(i).startsWith("conversation:")) {
let conversation = localStorage.getItem(localStorage.key(i));
conversations.push(JSON.parse(conversation));
}
}
//if (loader === undefined) spinner.parentNode.removeChild(spinner)
await clear_conversations();
for (conversation of conversations) {
box_conversations.innerHTML += `
<div class="convo" id="convo-${conversation.id}">
<div class="left" onclick="set_conversation('${conversation.id}')">
<i class="fa-regular fa-comments"></i>
<span class="convo-title">${conversation.title}</span>
</div>
<i onclick="show_option('${conversation.id}')" class="fa-regular fa-trash" id="conv-${conversation.id}"></i>
<i onclick="delete_conversation('${conversation.id}')" class="fa-regular fa-check" id="yes-${conversation.id}" style="display:none;"></i>
<i onclick="hide_option('${conversation.id}')" class="fa-regular fa-x" id="not-${conversation.id}" style="display:none;"></i>
</div>
`;
}
document.querySelectorAll(`code`).forEach((el) => {
hljs.highlightElement(el);
});
};
document.getElementById(`cancelButton`).addEventListener(`click`, async () => {
window.controller.abort();
console.log(`aborted ${window.conversation_id}`);
});
function h2a(str1) {
var hex = str1.toString();
var str = "";
for (var n = 0; n < hex.length; n += 2) {
str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
}
return str;
}
const uuid = () => {
return `xxxxxxxx-xxxx-4xxx-yxxx-${Date.now().toString(16)}`.replace(
/[xy]/g,
function (c) {
var r = (Math.random() * 16) | 0,
v = c == "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
}
);
};
const message_id = () => {
random_bytes = (Math.floor(Math.random() * 1338377565) + 2956589730).toString(
2
);
unix = Math.floor(Date.now() / 1000).toString(2);
return BigInt(`0b${unix}${random_bytes}`).toString();
};
window.onload = async () => {
load_settings_localstorage();
conversations = 0;
for (let i = 0; i < localStorage.length; i++) {
if (localStorage.key(i).startsWith("conversation:")) {
conversations += 1;
}
}
if (conversations == 0) localStorage.clear();
await setTimeout(() => {
load_conversations(20, 0);
}, 1);
if (!window.location.href.endsWith(`#`)) {
if (/{{chat_path}}\/.+/.test(window.location.href)) {
await load_conversation(window.conversation_id);
}
}
message_input.addEventListener(`keydown`, async (evt) => {
if (prompt_lock) return;
if (evt.keyCode === 13 && !evt.shiftKey) {
evt.preventDefault();
console.log('pressed enter');
await handle_ask();
} else {
message_input.style.removeProperty("height");
message_input.style.height = message_input.scrollHeight + 4 + "px";
}
});
send_button.addEventListener(`click`, async () => {
console.log("clicked send");
if (prompt_lock) return;
await handle_ask();
});
register_settings_localstorage();
};
document.querySelector(".mobile-sidebar").addEventListener("click", (event) => {
const sidebar = document.querySelector(".conversations");
if (sidebar.classList.contains("shown")) {
sidebar.classList.remove("shown");
event.target.classList.remove("rotated");
} else {
sidebar.classList.add("shown");
event.target.classList.add("rotated");
}
window.scrollTo(0, 0);
});
const register_settings_localstorage = async () => {
settings_ids = ["switch", "model", "jailbreak"];
settings_elements = settings_ids.map((id) => document.getElementById(id));
settings_elements.map((element) =>
element.addEventListener(`change`, async (event) => {
switch (event.target.type) {
case "checkbox":
localStorage.setItem(event.target.id, event.target.checked);
break;
case "select-one":
localStorage.setItem(event.target.id, event.target.selectedIndex);
break;
default:
console.warn("Unresolved element type");
}
})
);
};
const load_settings_localstorage = async () => {
settings_ids = ["switch", "model", "jailbreak"];
settings_elements = settings_ids.map((id) => document.getElementById(id));
settings_elements.map((element) => {
if (localStorage.getItem(element.id)) {
switch (element.type) {
case "checkbox":
element.checked = localStorage.getItem(element.id) === "true";
break;
case "select-one":
element.selectedIndex = parseInt(localStorage.getItem(element.id));
break;
default:
console.warn("Unresolved element type");
}
}
});
};
// Theme storage for recurring viewers
const storeTheme = function (theme) {
localStorage.setItem("theme", theme);
};
// set theme when visitor returns
const setTheme = function () {
const activeTheme = localStorage.getItem("theme");
colorThemes.forEach((themeOption) => {
if (themeOption.id === activeTheme) {
themeOption.checked = true;
}
});
// fallback for no :has() support
document.documentElement.className = activeTheme;
};
colorThemes.forEach((themeOption) => {
themeOption.addEventListener("click", () => {
storeTheme(themeOption.id);
// fallback for no :has() support
document.documentElement.className = themeOption.id;
});
});
function deleteMessage(token) {
const messageDivUser = document.getElementById(`user_${token}`)
const messageDivGpt = document.getElementById(`gpt_${token}`)
if (messageDivUser) messageDivUser.parentNode.remove();
if (messageDivGpt) messageDivGpt.parentNode.remove();
const conversation = JSON.parse(localStorage.getItem(`conversation:${window.conversation_id}`));
conversation.items = conversation.items.filter(item => item.token !== token);
localStorage.setItem(`conversation:${window.conversation_id}`, JSON.stringify(conversation));
const messages = document.getElementsByClassName("message");
if (messages.length === 0) {
delete_conversation(window.conversation_id);
};
}
document.onload = setTheme();

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
class CopyButtonPlugin{constructor(options={}){self.hook=options.hook;self.callback=options.callback}"after:highlightElement"({el,text}){let button=Object.assign(document.createElement("button"),{innerHTML:"Copy",className:"hljs-copy-button"});button.dataset.copied=false;el.parentElement.classList.add("hljs-copy-wrapper");el.parentElement.appendChild(button);el.parentElement.style.setProperty("--hljs-theme-background",window.getComputedStyle(el).backgroundColor);button.onclick=function(){if(!navigator.clipboard)return;let newText=text;if(hook&&typeof hook==="function"){newText=hook(text,el)||text}navigator.clipboard.writeText(newText).then(function(){button.innerHTML="Copied!";button.dataset.copied=true;let alert=Object.assign(document.createElement("div"),{role:"status",className:"hljs-copy-alert",innerHTML:"Copied to clipboard"});el.parentElement.appendChild(alert);setTimeout(()=>{button.innerHTML="Copy";button.dataset.copied=false;el.parentElement.removeChild(alert);alert=null},2e3)}).then(function(){if(typeof callback==="function")return callback(newText,el)})}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,155 @@
boost::asio::awaitable<void> FreeGpt::chatGptAi(std::shared_ptr<Channel> ch, nlohmann::json json) {
ScopeExit auto_exit{[&] { ch->close(); }};
boost::system::error_code err{};
constexpr std::string_view host = "chatgpt.ai";
constexpr std::string_view port = "443";
constexpr std::string_view user_agent{
R"(Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36)"};
boost::beast::http::request<boost::beast::http::empty_body> req{boost::beast::http::verb::get, "/", 11};
req.set(boost::beast::http::field::host, "chatgpt.ai");
req.set(boost::beast::http::field::user_agent, user_agent);
req.set("Accept", "*/*");
int recreate_num{0};
create_client:
boost::asio::ssl::context ctx(boost::asio::ssl::context::tls);
ctx.set_verify_mode(boost::asio::ssl::verify_none);
auto client = co_await createHttpClient(ctx, host, port);
if (!client.has_value()) {
SPDLOG_ERROR("createHttpClient: {}", client.error());
co_await ch->async_send(err, client.error(), use_nothrow_awaitable);
co_return;
}
auto& stream_ = client.value();
std::string chunk_body;
std::string cookie;
auto ret = co_await sendRequestRecvChunk(
ch, stream_, req, 200, [&ch, &chunk_body](std::string recv_str) { chunk_body.append(std::move(recv_str)); },
[&](const boost::beast::http::parser<false, boost::beast::http::empty_body>& p) {
auto& headers = p.get();
for (const auto& header : headers) {
if (boost::beast::http::to_string(header.name()) == "Set-Cookie") {
cookie = header.value();
return;
}
}
});
SPDLOG_ERROR("cookie: {}", cookie);
if (ret == Status::Close && recreate_num == 0) {
recreate_num++;
goto create_client;
}
if (ret == Status::HasError)
co_return;
static std::string pattern{R"(data-system='(.*?)')"};
std::vector<std::string> matches = findAll(pattern, chunk_body);
if (matches.empty()) {
SPDLOG_ERROR("parsing login failed");
co_await ch->async_send(err, chunk_body, use_nothrow_awaitable);
co_return;
}
auto html_unescape = [](const std::string& text) {
std::string result = text;
boost::replace_all(result, "&amp;", "&");
boost::replace_all(result, "&lt;", "<");
boost::replace_all(result, "&gt;", ">");
boost::replace_all(result, "&quot;", "\"");
boost::replace_all(result, "&#39;", "'");
return result;
};
std::string html_json_str;
std::regex regex("'(.*?)'");
std::smatch result;
if (std::regex_search(matches[0], result, regex))
html_json_str = html_unescape(result[1]);
if (html_json_str.empty()) {
SPDLOG_ERROR("extract json fail");
co_await ch->async_send(err, chunk_body, use_nothrow_awaitable);
co_return;
}
nlohmann::json j = nlohmann::json::parse(html_json_str, nullptr, false);
if (j.is_discarded()) {
SPDLOG_ERROR("json parse error");
co_await ch->async_send(err, "json parse error", use_nothrow_awaitable);
co_return;
}
SPDLOG_INFO("json: {}", j.dump());
auto prompt = json.at("meta").at("content").at("parts").at(0).at("content").get<std::string>();
boost::beast::http::request<boost::beast::http::string_body> request{boost::beast::http::verb::post,
"/wp-json/mwai-ui/v1/chats/submit", 11};
request.set(boost::beast::http::field::host, host);
request.set("authority", "chatgpt.ai");
request.set("accept", "*/*");
request.set("accept-language", R"(en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3)");
request.set("cache-control", "no-cache");
request.set("origin", "https://chatgpt.ai");
request.set("pragma", "no-cache");
request.set(boost::beast::http::field::referer, "https://chatgpt.ai/");
request.set("sec-ch-ua", R"("Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114")");
request.set("sec-ch-ua-mobile", "?0");
request.set("sec-ch-ua-platform", R"("Windows")");
request.set("sec-fetch-dest", "empty");
request.set("sec-fetch-mode", "cors");
request.set("sec-fetch-site", "same-origin");
request.set("Cookie", cookie);
request.set(boost::beast::http::field::user_agent, user_agent);
request.set("Content-Type", "application/json");
constexpr std::string_view json_str = R"({
"botId":"chatbot-9vy3t5",
"clientId":"",
"contextId":1048,
"id":"chatbot-9vy3t5",
"messages":[],
"newMessage":"hello",
"session":"N/A",
"stream":true
})";
nlohmann::json request_json = nlohmann::json::parse(json_str, nullptr, false);
request_json["botId"] = j["botId"];
request_json["clientId"] = "";
request_json["contextId"] = j["contextId"];
request_json["id"] = j["id"];
request_json["session"] = j["sessionId"];
request_json["newMessage"] = prompt;
SPDLOG_INFO("request: {}", request_json.dump());
request.body() = request_json.dump();
request.prepare_payload();
std::string recv;
co_await sendRequestRecvChunk(ch, stream_, request, 200, [&](std::string str) {
recv.append(str);
while (true) {
auto position = recv.find("\n");
if (position == std::string::npos)
break;
auto msg = recv.substr(0, position + 1);
recv.erase(0, position + 1);
msg.pop_back();
if (msg.empty())
continue;
auto fields = splitString(msg, "data: ");
boost::system::error_code err{};
nlohmann::json line_json = nlohmann::json::parse(fields.back(), nullptr, false);
if (line_json.is_discarded()) {
SPDLOG_ERROR("json parse error: [{}]", fields.back());
ch->try_send(err, std::format("json parse error: [{}]", fields.back()));
continue;
}
auto type = line_json["type"].get<std::string>();
if (type == "live")
ch->try_send(err, line_json["data"].get<std::string>());
}
});
co_return;
}

View File

@@ -0,0 +1,572 @@
#!/usr/bin/env python
#
# ===- git-clang-format - ClangFormat Git Integration ---------*- python -*--===#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# ===------------------------------------------------------------------------===#
r"""
clang-format git integration
============================
This file provides a clang-format integration for git. Put it somewhere in your
path and ensure that it is executable. Then, "git clang-format" will invoke
clang-format on the changes in current files or a specific commit.
For further details, run:
git clang-format -h
Requires Python 2.7 or Python 3
"""
from __future__ import absolute_import, division, print_function
import argparse
import collections
import contextlib
import errno
import os
import re
import subprocess
import sys
usage = 'git clang-format [OPTIONS] [<commit>] [<commit>] [--] [<file>...]'
desc = '''
If zero or one commits are given, run clang-format on all lines that differ
between the working directory and <commit>, which defaults to HEAD. Changes are
only applied to the working directory.
If two commits are given (requires --diff), run clang-format on all lines in the
second <commit> that differ from the first <commit>.
The following git-config settings set the default of the corresponding option:
clangFormat.binary
clangFormat.commit
clangFormat.extension
clangFormat.style
'''
# Name of the temporary index file in which save the output of clang-format.
# This file is created within the .git directory.
temp_index_basename = 'clang-format-index'
Range = collections.namedtuple('Range', 'start, count')
def main():
config = load_git_config()
# In order to keep '--' yet allow options after positionals, we need to
# check for '--' ourselves. (Setting nargs='*' throws away the '--', while
# nargs=argparse.REMAINDER disallows options after positionals.)
argv = sys.argv[1:]
try:
idx = argv.index('--')
except ValueError:
dash_dash = []
else:
dash_dash = argv[idx:]
argv = argv[:idx]
default_extensions = ','.join(
[
# From clang/lib/Frontend/FrontendOptions.cpp, all lower case
'c',
'h', # C
'm', # ObjC
'mm', # ObjC++
'cc',
'cp',
'cpp',
'c++',
'cxx',
'hh',
'hpp',
'hxx', # C++
'cu', # CUDA
# Other languages that clang-format supports
'proto',
'protodevel', # Protocol Buffers
'java', # Java
'js', # JavaScript
'ts', # TypeScript
'cs', # C Sharp
]
)
p = argparse.ArgumentParser(usage=usage, formatter_class=argparse.RawDescriptionHelpFormatter, description=desc)
p.add_argument('--binary', default=config.get('clangformat.binary', 'clang-format'), help='path to clang-format'),
p.add_argument(
'--commit', default=config.get('clangformat.commit', 'HEAD'), help='default commit to use if none is specified'
),
p.add_argument('--diff', action='store_true', help='print a diff instead of applying the changes')
p.add_argument(
'--extensions',
default=config.get('clangformat.extensions', default_extensions),
help=('comma-separated list of file extensions to format, ' 'excluding the period and case-insensitive'),
),
p.add_argument('-f', '--force', action='store_true', help='allow changes to unstaged files')
p.add_argument('-p', '--patch', action='store_true', help='select hunks interactively')
p.add_argument('-q', '--quiet', action='count', default=0, help='print less information')
p.add_argument('--style', default=config.get('clangformat.style', None), help='passed to clang-format'),
p.add_argument('-v', '--verbose', action='count', default=0, help='print extra information')
# We gather all the remaining positional arguments into 'args' since we need
# to use some heuristics to determine whether or not <commit> was present.
# However, to print pretty messages, we make use of metavar and help.
p.add_argument('args', nargs='*', metavar='<commit>', help='revision from which to compute the diff')
p.add_argument(
'ignored', nargs='*', metavar='<file>...', help='if specified, only consider differences in these files'
)
opts = p.parse_args(argv)
opts.verbose -= opts.quiet
del opts.quiet
commits, files = interpret_args(opts.args, dash_dash, opts.commit)
if len(commits) > 1:
if not opts.diff:
die('--diff is required when two commits are given')
else:
if len(commits) > 2:
die('at most two commits allowed; %d given' % len(commits))
changed_lines = compute_diff_and_extract_lines(commits, files)
if opts.verbose >= 1:
ignored_files = set(changed_lines)
filter_by_extension(changed_lines, opts.extensions.lower().split(','))
if opts.verbose >= 1:
ignored_files.difference_update(changed_lines)
if ignored_files:
print('Ignoring changes in the following files (wrong extension):')
for filename in ignored_files:
print(' %s' % filename)
if changed_lines:
print('Running clang-format on the following files:')
for filename in changed_lines:
print(' %s' % filename)
if not changed_lines:
print('no modified files to format')
return
# The computed diff outputs absolute paths, so we must cd before accessing
# those files.
cd_to_toplevel()
if len(commits) > 1:
old_tree = commits[1]
new_tree = run_clang_format_and_save_to_tree(
changed_lines, revision=commits[1], binary=opts.binary, style=opts.style
)
else:
old_tree = create_tree_from_workdir(changed_lines)
new_tree = run_clang_format_and_save_to_tree(changed_lines, binary=opts.binary, style=opts.style)
if opts.verbose >= 1:
print('old tree: %s' % old_tree)
print('new tree: %s' % new_tree)
if old_tree == new_tree:
if opts.verbose >= 0:
print('clang-format did not modify any files')
elif opts.diff:
print_diff(old_tree, new_tree)
else:
changed_files = apply_changes(old_tree, new_tree, force=opts.force, patch_mode=opts.patch)
if (opts.verbose >= 0 and not opts.patch) or opts.verbose >= 1:
print('changed files:')
for filename in changed_files:
print(' %s' % filename)
def load_git_config(non_string_options=None):
"""Return the git configuration as a dictionary.
All options are assumed to be strings unless in `non_string_options`, in which
is a dictionary mapping option name (in lower case) to either "--bool" or
"--int"."""
if non_string_options is None:
non_string_options = {}
out = {}
for entry in run('git', 'config', '--list', '--null').split('\0'):
if entry:
name, value = entry.split('\n', 1)
if name in non_string_options:
value = run('git', 'config', non_string_options[name], name)
out[name] = value
return out
def interpret_args(args, dash_dash, default_commit):
"""Interpret `args` as "[commits] [--] [files]" and return (commits, files).
It is assumed that "--" and everything that follows has been removed from
args and placed in `dash_dash`.
If "--" is present (i.e., `dash_dash` is non-empty), the arguments to its
left (if present) are taken as commits. Otherwise, the arguments are checked
from left to right if they are commits or files. If commits are not given,
a list with `default_commit` is used."""
if dash_dash:
if len(args) == 0:
commits = [default_commit]
else:
commits = args
for commit in commits:
object_type = get_object_type(commit)
if object_type not in ('commit', 'tag'):
if object_type is None:
die("'%s' is not a commit" % commit)
else:
die("'%s' is a %s, but a commit was expected" % (commit, object_type))
files = dash_dash[1:]
elif args:
commits = []
while args:
if not disambiguate_revision(args[0]):
break
commits.append(args.pop(0))
if not commits:
commits = [default_commit]
files = args
else:
commits = [default_commit]
files = []
return commits, files
def disambiguate_revision(value):
"""Returns True if `value` is a revision, False if it is a file, or dies."""
# If `value` is ambiguous (neither a commit nor a file), the following
# command will die with an appropriate error message.
run('git', 'rev-parse', value, verbose=False)
object_type = get_object_type(value)
if object_type is None:
return False
if object_type in ('commit', 'tag'):
return True
die('`%s` is a %s, but a commit or filename was expected' % (value, object_type))
def get_object_type(value):
"""Returns a string description of an object's type, or None if it is not
a valid git object."""
cmd = ['git', 'cat-file', '-t', value]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
return None
return convert_string(stdout.strip())
def compute_diff_and_extract_lines(commits, files):
"""Calls compute_diff() followed by extract_lines()."""
diff_process = compute_diff(commits, files)
changed_lines = extract_lines(diff_process.stdout)
diff_process.stdout.close()
diff_process.wait()
if diff_process.returncode != 0:
# Assume error was already printed to stderr.
sys.exit(2)
return changed_lines
def compute_diff(commits, files):
"""Return a subprocess object producing the diff from `commits`.
The return value's `stdin` file object will produce a patch with the
differences between the working directory and the first commit if a single
one was specified, or the difference between both specified commits, filtered
on `files` (if non-empty). Zero context lines are used in the patch."""
git_tool = 'diff-index'
if len(commits) > 1:
git_tool = 'diff-tree'
cmd = ['git', git_tool, '-p', '-U0'] + commits + ['--']
cmd.extend(files)
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.close()
return p
def extract_lines(patch_file):
"""Extract the changed lines in `patch_file`.
The return value is a dictionary mapping filename to a list of (start_line,
line_count) pairs.
The input must have been produced with ``-U0``, meaning unidiff format with
zero lines of context. The return value is a dict mapping filename to a
list of line `Range`s."""
matches = {}
for line in patch_file:
line = convert_string(line)
match = re.search(r'^\+\+\+\ [^/]+/(.*)', line)
if match:
filename = match.group(1).rstrip('\r\n')
match = re.search(r'^@@ -[0-9,]+ \+(\d+)(,(\d+))?', line)
if match:
start_line = int(match.group(1))
line_count = 1
if match.group(3):
line_count = int(match.group(3))
if line_count > 0:
matches.setdefault(filename, []).append(Range(start_line, line_count))
return matches
def filter_by_extension(dictionary, allowed_extensions):
"""Delete every key in `dictionary` that doesn't have an allowed extension.
`allowed_extensions` must be a collection of lowercase file extensions,
excluding the period."""
allowed_extensions = frozenset(allowed_extensions)
for filename in list(dictionary.keys()):
base_ext = filename.rsplit('.', 1)
if len(base_ext) == 1 and '' in allowed_extensions:
continue
if len(base_ext) == 1 or base_ext[1].lower() not in allowed_extensions:
del dictionary[filename]
def cd_to_toplevel():
"""Change to the top level of the git repository."""
toplevel = run('git', 'rev-parse', '--show-toplevel')
os.chdir(toplevel)
def create_tree_from_workdir(filenames):
"""Create a new git tree with the given files from the working directory.
Returns the object ID (SHA-1) of the created tree."""
return create_tree(filenames, '--stdin')
def run_clang_format_and_save_to_tree(changed_lines, revision=None, binary='clang-format', style=None):
"""Run clang-format on each file and save the result to a git tree.
Returns the object ID (SHA-1) of the created tree."""
def iteritems(container):
try:
return container.iteritems() # Python 2
except AttributeError:
return container.items() # Python 3
def index_info_generator():
for filename, line_ranges in iteritems(changed_lines):
if revision:
git_metadata_cmd = [
'git',
'ls-tree',
'%s:%s' % (revision, os.path.dirname(filename)),
os.path.basename(filename),
]
git_metadata = subprocess.Popen(git_metadata_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout = git_metadata.communicate()[0]
mode = oct(int(stdout.split()[0], 8))
else:
mode = oct(os.stat(filename).st_mode)
# Adjust python3 octal format so that it matches what git expects
if mode.startswith('0o'):
mode = '0' + mode[2:]
blob_id = clang_format_to_blob(filename, line_ranges, revision=revision, binary=binary, style=style)
yield '%s %s\t%s' % (mode, blob_id, filename)
return create_tree(index_info_generator(), '--index-info')
def create_tree(input_lines, mode):
"""Create a tree object from the given input.
If mode is '--stdin', it must be a list of filenames. If mode is
'--index-info' is must be a list of values suitable for "git update-index
--index-info", such as "<mode> <SP> <sha1> <TAB> <filename>". Any other mode
is invalid."""
assert mode in ('--stdin', '--index-info')
cmd = ['git', 'update-index', '--add', '-z', mode]
with temporary_index_file():
p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
for line in input_lines:
p.stdin.write(to_bytes('%s\0' % line))
p.stdin.close()
if p.wait() != 0:
die('`%s` failed' % ' '.join(cmd))
tree_id = run('git', 'write-tree')
return tree_id
def clang_format_to_blob(filename, line_ranges, revision=None, binary='clang-format', style=None):
"""Run clang-format on the given file and save the result to a git blob.
Runs on the file in `revision` if not None, or on the file in the working
directory if `revision` is None.
Returns the object ID (SHA-1) of the created blob."""
clang_format_cmd = [binary]
if style:
clang_format_cmd.extend(['-style=' + style])
clang_format_cmd.extend(
['-lines=%s:%s' % (start_line, start_line + line_count - 1) for start_line, line_count in line_ranges]
)
if revision:
clang_format_cmd.extend(['-assume-filename=' + filename])
git_show_cmd = ['git', 'cat-file', 'blob', '%s:%s' % (revision, filename)]
git_show = subprocess.Popen(git_show_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
git_show.stdin.close()
clang_format_stdin = git_show.stdout
else:
clang_format_cmd.extend([filename])
git_show = None
clang_format_stdin = subprocess.PIPE
try:
clang_format = subprocess.Popen(clang_format_cmd, stdin=clang_format_stdin, stdout=subprocess.PIPE)
if clang_format_stdin == subprocess.PIPE:
clang_format_stdin = clang_format.stdin
except OSError as e:
if e.errno == errno.ENOENT:
die('cannot find executable "%s"' % binary)
else:
raise
clang_format_stdin.close()
hash_object_cmd = ['git', 'hash-object', '-w', '--path=' + filename, '--stdin']
hash_object = subprocess.Popen(hash_object_cmd, stdin=clang_format.stdout, stdout=subprocess.PIPE)
clang_format.stdout.close()
stdout = hash_object.communicate()[0]
if hash_object.returncode != 0:
die('`%s` failed' % ' '.join(hash_object_cmd))
if clang_format.wait() != 0:
die('`%s` failed' % ' '.join(clang_format_cmd))
if git_show and git_show.wait() != 0:
die('`%s` failed' % ' '.join(git_show_cmd))
return convert_string(stdout).rstrip('\r\n')
@contextlib.contextmanager
def temporary_index_file(tree=None):
"""Context manager for setting GIT_INDEX_FILE to a temporary file and deleting
the file afterward."""
index_path = create_temporary_index(tree)
old_index_path = os.environ.get('GIT_INDEX_FILE')
os.environ['GIT_INDEX_FILE'] = index_path
try:
yield
finally:
if old_index_path is None:
del os.environ['GIT_INDEX_FILE']
else:
os.environ['GIT_INDEX_FILE'] = old_index_path
os.remove(index_path)
def create_temporary_index(tree=None):
"""Create a temporary index file and return the created file's path.
If `tree` is not None, use that as the tree to read in. Otherwise, an
empty index is created."""
gitdir = run('git', 'rev-parse', '--git-dir')
path = os.path.join(gitdir, temp_index_basename)
if tree is None:
tree = '--empty'
run('git', 'read-tree', '--index-output=' + path, tree)
return path
def print_diff(old_tree, new_tree):
"""Print the diff between the two trees to stdout."""
# We use the porcelain 'diff' and not plumbing 'diff-tree' because the output
# is expected to be viewed by the user, and only the former does nice things
# like color and pagination.
#
# We also only print modified files since `new_tree` only contains the files
# that were modified, so unmodified files would show as deleted without the
# filter.
subprocess.check_call(['git', 'diff', '--diff-filter=M', old_tree, new_tree, '--'])
def apply_changes(old_tree, new_tree, force=False, patch_mode=False):
"""Apply the changes in `new_tree` to the working directory.
Bails if there are local changes in those files and not `force`. If
`patch_mode`, runs `git checkout --patch` to select hunks interactively."""
changed_files = (
run('git', 'diff-tree', '--diff-filter=M', '-r', '-z', '--name-only', old_tree, new_tree)
.rstrip('\0')
.split('\0')
)
if not force:
unstaged_files = run('git', 'diff-files', '--name-status', *changed_files)
if unstaged_files:
print('The following files would be modified but ' 'have unstaged changes:', file=sys.stderr)
print(unstaged_files, file=sys.stderr)
print('Please commit, stage, or stash them first.', file=sys.stderr)
sys.exit(2)
if patch_mode:
# In patch mode, we could just as well create an index from the new tree
# and checkout from that, but then the user will be presented with a
# message saying "Discard ... from worktree". Instead, we use the old
# tree as the index and checkout from new_tree, which gives the slightly
# better message, "Apply ... to index and worktree". This is not quite
# right, since it won't be applied to the user's index, but oh well.
with temporary_index_file(old_tree):
subprocess.check_call(['git', 'checkout', '--patch', new_tree])
else:
with temporary_index_file(new_tree):
run('git', 'checkout-index', '-a', '-f')
return changed_files
def run(*args, **kwargs):
stdin = kwargs.pop('stdin', '')
verbose = kwargs.pop('verbose', True)
strip = kwargs.pop('strip', True)
for name in kwargs:
raise TypeError("run() got an unexpected keyword argument '%s'" % name)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout, stderr = p.communicate(input=stdin)
stdout = convert_string(stdout)
stderr = convert_string(stderr)
if p.returncode == 0:
if stderr:
if verbose:
print('`%s` printed to stderr:' % ' '.join(args), file=sys.stderr)
print(stderr.rstrip(), file=sys.stderr)
if strip:
stdout = stdout.rstrip('\r\n')
return stdout
if verbose:
print('`%s` returned %s' % (' '.join(args), p.returncode), file=sys.stderr)
if stderr:
print(stderr.rstrip(), file=sys.stderr)
sys.exit(2)
def die(message):
print('error:', message, file=sys.stderr)
sys.exit(2)
def to_bytes(str_input):
# Encode to UTF-8 to get binary data.
if isinstance(str_input, bytes):
return str_input
return str_input.encode('utf-8')
def to_string(bytes_input):
if isinstance(bytes_input, str):
return bytes_input
return bytes_input.encode('utf-8')
def convert_string(bytes_input):
try:
return to_string(bytes_input.decode('utf-8'))
except AttributeError: # 'str' object has no attribute 'decode'.
return str(bytes_input)
except UnicodeError:
return str(bytes_input)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,19 @@
#pragma once
#include <yaml_cpp_struct.hpp>
struct Config {
std::string client_root_path;
std::size_t interval{300};
std::size_t work_thread_num{8};
std::string host{"0.0.0.0"};
std::string port{"8858"};
std::string chat_path{"/chat"};
std::vector<std::string> providers;
bool enable_proxy;
std::string http_proxy;
std::string api_key;
std::vector<std::string> ip_white_list;
};
YCS_ADD_STRUCT(Config, client_root_path, interval, work_thread_num, host, port, chat_path, providers, enable_proxy,
http_proxy, api_key, ip_white_list)

View File

@@ -0,0 +1,52 @@
#pragma once
#include <expected>
#include <memory>
#include <boost/asio/awaitable.hpp>
#include <boost/asio/experimental/channel.hpp>
#include <boost/asio/thread_pool.hpp>
#include <boost/beast.hpp>
#include <boost/beast/ssl.hpp>
#include <nlohmann/json.hpp>
#include "cfg.h"
class FreeGpt final {
public:
using Channel = boost::asio::experimental::channel<void(boost::system::error_code, std::string)>;
FreeGpt(Config&);
boost::asio::awaitable<void> aiTianhu(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> aiTianhuSpace(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> deepAi(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> aiChat(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> chatGptAi(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> acytoo(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> openAi(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> h2o(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> yqcloud(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> huggingChat(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> you(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> binjie(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> chatBase(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> aivvm(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> ylokh(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> vitalentum(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> gptGo(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> aibn(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> chatGptDuo(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> chatForAi(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> freeGpt(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> cromicle(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> chatGpt4Online(std::shared_ptr<Channel>, nlohmann::json);
boost::asio::awaitable<void> gptalk(std::shared_ptr<Channel>, nlohmann::json);
private:
boost::asio::awaitable<std::expected<boost::beast::ssl_stream<boost::beast::tcp_stream>, std::string>>
createHttpClient(boost::asio::ssl::context&, std::string_view /* host */, std::string_view /* port */);
Config& m_cfg;
std::shared_ptr<boost::asio::thread_pool> m_thread_pool_ptr;
};

View File

@@ -0,0 +1,103 @@
#pragma once
#include <list>
#include <thread>
#include <vector>
#include <boost/asio.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
constexpr auto use_nothrow_awaitable = boost::asio::as_tuple(boost::asio::use_awaitable);
class IoContextPool final {
public:
explicit IoContextPool(std::size_t);
void start();
void stop();
boost::asio::io_context& getIoContext();
private:
std::vector<std::shared_ptr<boost::asio::io_context>> m_io_contexts;
std::list<boost::asio::any_io_executor> m_work;
std::size_t m_next_io_context;
std::vector<std::jthread> m_threads;
};
inline IoContextPool::IoContextPool(std::size_t pool_size) : m_next_io_context(0) {
if (pool_size == 0)
throw std::runtime_error("IoContextPool size is 0");
for (std::size_t i = 0; i < pool_size; ++i) {
auto io_context_ptr = std::make_shared<boost::asio::io_context>();
m_io_contexts.emplace_back(io_context_ptr);
m_work.emplace_back(
boost::asio::require(io_context_ptr->get_executor(), boost::asio::execution::outstanding_work.tracked));
}
}
inline void IoContextPool::start() {
for (auto& context : m_io_contexts)
m_threads.emplace_back(std::jthread([&] { context->run(); }));
}
inline void IoContextPool::stop() {
for (auto& context_ptr : m_io_contexts)
context_ptr->stop();
}
inline boost::asio::io_context& IoContextPool::getIoContext() {
boost::asio::io_context& io_context = *m_io_contexts[m_next_io_context];
++m_next_io_context;
if (m_next_io_context == m_io_contexts.size())
m_next_io_context = 0;
return io_context;
}
inline boost::asio::awaitable<void> timeout(std::chrono::seconds duration) {
auto now = std::chrono::steady_clock::now() + duration;
boost::asio::steady_timer timer(co_await boost::asio::this_coro::executor);
timer.expires_at(now);
[[maybe_unused]] auto [ec] = co_await timer.async_wait(boost::asio::as_tuple(boost::asio::use_awaitable));
co_return;
}
template <typename... Args>
inline auto getEnv(Args&&... args) {
auto impl = []<std::size_t... I>(auto&& tp, std::index_sequence<I...>) {
auto func = [](std::string_view env_name) {
const char* env = std::getenv(env_name.data());
if (env == nullptr)
return std::string{};
return std::string{env};
};
return std::make_tuple(func(std::get<I>(tp))...);
};
return impl(std::forward_as_tuple(args...), std::index_sequence_for<Args...>{});
}
class ScopeExit {
public:
ScopeExit(const ScopeExit&) = delete;
ScopeExit& operator=(const ScopeExit&) = delete;
template <typename Callable>
explicit ScopeExit(Callable&& call) : m_call(std::forward<Callable>(call)) {}
~ScopeExit() {
if (m_call)
m_call();
}
void clear() { m_call = decltype(m_call)(); }
private:
std::function<void()> m_call;
};
inline std::string createUuidString() {
static thread_local boost::uuids::random_generator gen;
return boost::uuids::to_string(gen());
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,394 @@
#define OPEN_YAML_TO_JSON
#include <format>
#include <functional>
#include <regex>
#include <semaphore>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <boost/asio/as_tuple.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/experimental/awaitable_operators.hpp>
#include <curl/curl.h>
#include <spdlog/spdlog.h>
#include <inja/inja.hpp>
#include "cfg.h"
#include "free_gpt.h"
#include "helper.hpp"
constexpr std::string_view ASSETS_PATH{"/assets"};
constexpr std::string_view API_PATH{"/backend-api/v2/conversation"};
using GptCallback = std::function<boost::asio::awaitable<void>(std::shared_ptr<FreeGpt::Channel>, nlohmann::json)>;
inline std::unordered_map<std::string, GptCallback> gpt_function;
#define ADD_METHOD(name, function) gpt_function[name] = std::bind_front(&function, app);
void setEnvironment(auto& cfg) {
setenv("CURL_IMPERSONATE", "chrome110", 1);
if (cfg.enable_proxy) {
auto [lower_http_proxy, upper_http_proxy] = getEnv("http_proxy", "HTTP_PROXY");
if (!lower_http_proxy.empty())
cfg.http_proxy = std::move(lower_http_proxy);
if (!upper_http_proxy.empty())
cfg.http_proxy = std::move(upper_http_proxy);
}
if (auto [chat_path] = getEnv("CHAT_PATH"); !chat_path.empty()) {
cfg.chat_path = std::move(chat_path);
}
if (cfg.chat_path.back() == '/')
cfg.chat_path.pop_back();
if (auto [port] = getEnv("PORT"); !port.empty())
cfg.port = std::move(port);
if (auto [host] = getEnv("HOST"); !host.empty())
cfg.host = std::move(host);
if (auto [work_thread_num] = getEnv("WORK_THREAD_NUM"); !work_thread_num.empty())
cfg.work_thread_num = std::atol(work_thread_num.c_str());
if (auto [providers] = getEnv("PROVIDERS"); !providers.empty()) {
nlohmann::json providers_list = nlohmann::json::parse(providers, nullptr, false);
if (!providers_list.is_discarded())
cfg.providers = providers_list.get<std::vector<std::string>>();
}
if (auto [api_key] = getEnv("API_KEY"); !api_key.empty())
cfg.api_key = std::move(api_key);
if (auto [interval] = getEnv("INTERVAL"); !interval.empty())
cfg.interval = std::atol(interval.c_str());
// export IP_WHITE_LIST="[\"127.0.0.1\",\"192.168.1.1\"]"
if (auto [ip_white_list_str] = getEnv("IP_WHITE_LIST"); !ip_white_list_str.empty()) {
nlohmann::json ip_white_list = nlohmann::json::parse(ip_white_list_str, nullptr, false);
if (!ip_white_list.is_discarded())
cfg.ip_white_list = ip_white_list.get<std::vector<std::string>>();
}
}
std::string createIndexHtml(const std::string& file, const Config& cfg) {
inja::Environment env;
nlohmann::json data;
data["chat_id"] = createUuidString();
data["chat_path"] = cfg.chat_path;
if (!cfg.providers.empty()) {
data["model_list"] = cfg.providers;
} else {
for (auto&& m : std::views::keys(gpt_function))
data["model_list"].emplace_back(m);
}
return env.render_file(file, data);
}
boost::asio::awaitable<void> sendHttpResponse(auto& stream, auto& request, auto status) {
boost::beast::http::response<boost::beast::http::string_body> res{status, request.version()};
res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(boost::beast::http::field::content_type, "text/html");
res.keep_alive(request.keep_alive());
res.prepare_payload();
boost::beast::http::message_generator rsp = std::move(res);
co_await boost::beast::async_write(stream, std::move(rsp), use_nothrow_awaitable);
co_return;
}
void setContentType(auto& res, const std::string& file) {
SPDLOG_INFO("file: {}", file);
if (file.ends_with("js")) {
res.set(boost::beast::http::field::content_type, "text/javascript");
} else if (file.ends_with("css")) {
res.set(boost::beast::http::field::content_type, "text/css");
} else if (file.ends_with("png")) {
res.set(boost::beast::http::field::content_type, "image/png");
} else
SPDLOG_ERROR("invalid file type: {}", file);
}
boost::asio::awaitable<void> startSession(boost::asio::ip::tcp::socket sock, Config& cfg,
boost::asio::io_context& context) {
boost::beast::tcp_stream stream{std::move(sock)};
using namespace boost::asio::experimental::awaitable_operators;
ScopeExit auto_exit{[&stream] {
boost::beast::error_code ec;
stream.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
}};
boost::beast::error_code ec{};
boost::asio::ip::tcp::endpoint endpoint = boost::beast::get_lowest_layer(stream).socket().remote_endpoint(ec);
if (ec) {
SPDLOG_ERROR("get remote_endpoint error: {}", ec.message());
co_return;
}
std::string remote_ip{endpoint.address().to_string()};
if (!cfg.ip_white_list.empty() && std::ranges::find(cfg.ip_white_list, remote_ip) == cfg.ip_white_list.end()) {
SPDLOG_INFO("[{}] not in ip white list.", remote_ip);
boost::beast::http::response<boost::beast::http::string_body> res{boost::beast::http::status::unauthorized,
11};
res.set(boost::beast::http::field::server, "CppFreeGpt");
res.body() = "Invalid IP address";
res.prepare_payload();
boost::beast::http::message_generator rsp = std::move(res);
co_await boost::beast::async_write(stream, std::move(rsp), use_nothrow_awaitable);
co_return;
}
auto assets_path = std::format("{}{}", cfg.chat_path, ASSETS_PATH);
SPDLOG_INFO("assets_path: [{}]", assets_path);
while (true) {
boost::beast::flat_buffer buffer;
boost::beast::http::request<boost::beast::http::string_body> request;
auto result = co_await (boost::beast::http::async_read(stream, buffer, request, use_nothrow_awaitable) ||
timeout(std::chrono::seconds(cfg.interval)));
if (result.index() == 1) {
SPDLOG_INFO("read timeout");
co_return;
}
auto [ec, bytes_transferred] = std::get<0>(result);
if (ec) {
SPDLOG_INFO("async_read: {}", ec.message());
co_return;
}
bool keep_alive = request.keep_alive();
auto http_path = request.target();
if (http_path.back() == '/')
http_path.remove_suffix(1);
if (http_path == cfg.chat_path) {
auto html = createIndexHtml(std::format("{}/html/index.html", cfg.client_root_path), cfg);
boost::beast::http::response<boost::beast::http::string_body> res{boost::beast::http::status::ok,
request.version()};
res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(boost::beast::http::field::content_type, "text/html");
res.keep_alive(request.keep_alive());
res.body() = std::move(html);
res.prepare_payload();
boost::beast::http::message_generator rsp = std::move(res);
co_await boost::beast::async_write(stream, std::move(rsp), use_nothrow_awaitable);
} else if (request.target().starts_with(assets_path)) {
std::string req_path{request.target()};
SPDLOG_INFO("req_path: {}", req_path);
req_path.erase(req_path.find(assets_path), assets_path.length());
auto file = std::format("{}{}", cfg.client_root_path, req_path);
SPDLOG_INFO("load: {}", file);
if (file.contains("chat.js") || file.contains("site.webmanifest")) {
inja::Environment env;
nlohmann::json data;
if (file.contains("chat.js")) {
auto format_string = [](const std::string& str) {
std::regex pattern("/");
std::string replacement = "\\/";
return std::regex_replace(str, pattern, replacement);
};
data["chat_path"] = format_string(cfg.chat_path);
} else {
data["chat_path"] = cfg.chat_path;
}
auto chat_js_content = env.render_file(file, data);
boost::beast::http::response<boost::beast::http::string_body> res{boost::beast::http::status::ok,
request.version()};
res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING);
setContentType(res, file);
res.keep_alive(request.keep_alive());
res.body() = std::move(chat_js_content);
res.prepare_payload();
boost::beast::http::message_generator rsp = std::move(res);
co_await boost::beast::async_write(stream, std::move(rsp), use_nothrow_awaitable);
} else {
boost::beast::error_code ec;
boost::beast::http::file_body::value_type body;
body.open(file.c_str(), boost::beast::file_mode::scan, ec);
if (ec == boost::beast::errc::no_such_file_or_directory) {
co_await sendHttpResponse(stream, request, boost::beast::http::status::not_found);
co_return;
}
auto const size = body.size();
boost::beast::http::response<boost::beast::http::file_body> res{
std::piecewise_construct, std::make_tuple(std::move(body)),
std::make_tuple(boost::beast::http::status::ok, request.version())};
res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING);
setContentType(res, file);
res.content_length(size);
res.keep_alive(request.keep_alive());
boost::beast::http::message_generator rsp = std::move(res);
co_await boost::beast::async_write(stream, std::move(rsp), use_nothrow_awaitable);
}
} else if (request.target() == API_PATH) {
std::string model;
nlohmann::json request_body;
bool flag = false;
try {
request_body = nlohmann::json::parse(request.body());
model = request_body.at("model");
auto prompt = request_body.at("meta").at("content").at("parts").at(0).at("content");
auto conversation = request_body.at("meta").at("content").at("conversation");
} catch (const nlohmann::json::exception& e) {
SPDLOG_ERROR("nlohmann json: [{}], [{}]", e.what(), request.body());
flag = true;
}
if (flag) {
co_await sendHttpResponse(stream, request, boost::beast::http::status::bad_request);
co_return;
}
boost::beast::http::response<boost::beast::http::buffer_body> res;
res.result(boost::beast::http::status::ok);
res.version(request.version());
res.set(boost::beast::http::field::server, "CppFreeGpt");
res.set(boost::beast::http::field::transfer_encoding, "chunked");
res.set(boost::beast::http::field::content_type, "text/event-stream");
res.body().data = nullptr;
res.body().more = true;
boost::beast::http::response_serializer<boost::beast::http::buffer_body, boost::beast::http::fields> sr{
res};
auto [ec, count] = co_await boost::beast::http::async_write_header(stream, sr, use_nothrow_awaitable);
if (ec) {
SPDLOG_ERROR("{}", ec.message());
co_return;
}
if (!gpt_function.contains(model)) {
SPDLOG_ERROR("Invalid request model: {}", model);
static std::string reject{"Invalid request model"};
res.body().data = reject.data();
res.body().size = reject.size();
res.body().more = false;
std::tie(ec, count) = co_await boost::beast::http::async_write(stream, sr, use_nothrow_awaitable);
co_return;
}
auto ch = std::make_shared<FreeGpt::Channel>(co_await boost::asio::this_coro::executor, 4096);
boost::asio::co_spawn(
context,
[](auto ch, auto model, auto request_body) -> boost::asio::awaitable<void> {
auto& func = gpt_function[model];
co_await func(std::move(ch), std::move(request_body));
co_return;
}(ch, std::move(model), std::move(request_body)),
[](std::exception_ptr eptr) {
try {
if (eptr)
std::rethrow_exception(eptr);
} catch (const std::exception& e) {
SPDLOG_ERROR("Caught exception: {}", e.what());
}
});
while (true) {
auto [ec, str] = co_await ch->async_receive(use_nothrow_awaitable);
if (ec) {
break;
}
res.body().data = str.data();
res.body().size = str.size();
res.body().more = true;
std::tie(ec, count) = co_await boost::beast::http::async_write(stream, sr, use_nothrow_awaitable);
}
res.body().data = nullptr;
res.body().more = false;
std::tie(ec, count) = co_await boost::beast::http::async_write(stream, sr, use_nothrow_awaitable);
} else {
SPDLOG_ERROR("bad_request: [{}], Expected path is: [{}]", request.target(), cfg.chat_path);
co_await sendHttpResponse(stream, request, boost::beast::http::status::bad_request);
co_return;
}
if (!keep_alive)
co_return;
}
co_return;
}
boost::asio::awaitable<void> doSession(boost::asio::ip::tcp::acceptor& acceptor, IoContextPool& pool, Config& cfg) {
for (;;) {
auto& context = pool.getIoContext();
boost::asio::ip::tcp::socket socket(context);
auto [ec] = co_await acceptor.async_accept(socket, use_nothrow_awaitable);
if (ec) {
if (ec == boost::asio::error::operation_aborted)
break;
SPDLOG_ERROR("Accept failed, error: {}", ec.message());
continue;
}
boost::asio::co_spawn(context, startSession(std::move(socket), cfg, context), boost::asio::detached);
}
co_return;
}
int main(int argc, char** argv) {
curl_global_init(CURL_GLOBAL_ALL);
ScopeExit cleanup{[=] { curl_global_cleanup(); }};
spdlog::set_pattern("[%Y-%m-%d %H:%M:%S.%e][thread %t][%!][%s:%#][%l] %v");
auto [config, error] = yaml_cpp_struct::from_yaml<Config>(argv[1]);
if (!config) {
SPDLOG_ERROR("{}", error);
return EXIT_FAILURE;
}
auto& cfg = config.value();
setEnvironment(cfg);
auto [yaml_cfg_str, _] = yaml_cpp_struct::to_yaml(cfg);
SPDLOG_INFO("\n{}", yaml_cpp_struct::yaml_to_json(yaml_cfg_str.value()).dump(2));
std::cout << "\033[32m"
<< "GitHub: https://github.com/fantasy-peak/cpp-freegpt-webui"
<< "\033[0m" << std::endl;
FreeGpt app{cfg};
if (!cfg.api_key.empty())
ADD_METHOD("gpt-3.5-turbo-stream-openai", FreeGpt::openAi);
ADD_METHOD("gpt-4-ChatgptAi", FreeGpt::chatGptAi);
ADD_METHOD("gpt-3.5-turbo-stream-DeepAi", FreeGpt::deepAi);
ADD_METHOD("gpt-3.5-turbo-stream-H2o", FreeGpt::h2o);
ADD_METHOD("gpt-3.5-turbo-stream-yqcloud", FreeGpt::yqcloud);
ADD_METHOD("gpt-OpenAssistant-stream-HuggingChat", FreeGpt::huggingChat)
ADD_METHOD("gpt-4-turbo-stream-you", FreeGpt::you);
ADD_METHOD("gpt-3-stream-binjie", FreeGpt::binjie);
ADD_METHOD("gpt-4-stream-ChatBase", FreeGpt::chatBase);
ADD_METHOD("gpt-3.5-turbo-stream-aivvm", FreeGpt::aivvm);
ADD_METHOD("gpt-3.5-turbo-16k-stream-Ylokh", FreeGpt::ylokh);
ADD_METHOD("gpt-3.5-turbo-stream-Vitalentum", FreeGpt::vitalentum);
ADD_METHOD("gpt-3.5-turbo-stream-GptGo", FreeGpt::gptGo);
ADD_METHOD("gpt-3.5-turbo-stream-Aibn", FreeGpt::aibn);
ADD_METHOD("gpt-3.5-turbo-ChatgptDuo", FreeGpt::chatGptDuo);
ADD_METHOD("gpt-3.5-turbo-stream-FreeGpt", FreeGpt::freeGpt);
ADD_METHOD("gpt-3.5-turbo-stream-Cromicle", FreeGpt::cromicle);
ADD_METHOD("gpt-4-stream-Chatgpt4Online", FreeGpt::chatGpt4Online);
ADD_METHOD("gpt-3.5-turbo-stream-gptalk", FreeGpt::gptalk);
// ADD_METHOD("gpt-3.5-turbo-Aichat", FreeGpt::aiChat);
// ADD_METHOD("gpt-3.5-turbo-stream-ChatForAi", FreeGpt::chatForAi);
// ADD_METHOD("gpt-3.5-turbo-stream-AItianhuSpace", FreeGpt::aiTianhuSpace);
// ADD_METHOD("gpt-3.5-turbo-AItianhu", FreeGpt::aiTianhu);
// ADD_METHOD("gpt-3.5-turbo-acytoo", FreeGpt::acytoo);
IoContextPool pool{cfg.work_thread_num};
pool.start();
IoContextPool accept_pool{1};
accept_pool.start();
auto& context = accept_pool.getIoContext();
boost::asio::ip::tcp::acceptor acceptor(context);
boost::asio::ip::tcp::resolver resolver(context);
boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(cfg.host, cfg.port).begin();
acceptor.open(endpoint.protocol());
boost::system::error_code ec;
acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
SPDLOG_INFO("server start accept at {}:{} ...", endpoint.address().to_string(), cfg.port);
acceptor.listen(boost::asio::socket_base::max_listen_connections, ec);
if (ec) {
SPDLOG_ERROR("{}", ec.message());
return EXIT_FAILURE;
}
boost::asio::co_spawn(context, doSession(acceptor, pool, cfg), boost::asio::detached);
boost::asio::signal_set sigset(context, SIGINT, SIGTERM);
std::binary_semaphore smph_signal_main_to_thread{0};
sigset.async_wait([&](const boost::system::error_code&, int) {
acceptor.close();
smph_signal_main_to_thread.release();
});
smph_signal_main_to_thread.acquire();
SPDLOG_INFO("stoped ...");
accept_pool.stop();
pool.stop();
return EXIT_SUCCESS;
}

View File

@@ -0,0 +1,22 @@
set_project("cpp-freegpt-webui")
set_version("0.0.1", {build = "%Y%m%d%H%M"})
set_xmakever("2.7.8")
add_repositories("my_private_repo https://github.com/fantasy-peak/xmake-repo.git")
add_requires("openssl", {system = false})
add_requires("zlib", {system = false})
add_requires("yaml_cpp_struct", "nlohmann_json", "spdlog", "inja", "plusaes")
add_requires("boost", {configs = {iostreams = true}})
set_languages("c++23")
set_policy("check.auto_ignore_flags", false)
add_cxflags("-O2 -Wall -Wextra -pedantic-errors -Wno-missing-field-initializers -Wno-ignored-qualifiers")
add_includedirs("include")
target("cpp-freegpt-webui")
set_kind("binary")
add_files("src/*.cpp")
add_packages("openssl", "yaml_cpp_struct", "nlohmann_json", "spdlog", "boost", "inja", "plusaes", "zlib")
add_syslinks("pthread", "curl-impersonate-chrome")
target_end()