change chat gpt provider (#12)

This commit is contained in:
Dmitry Afanasyev 2023-09-26 19:15:13 +03:00 committed by GitHub
parent 665bb51c0c
commit d6afab4ee4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
145 changed files with 6146 additions and 7652 deletions

View File

@ -67,7 +67,11 @@ jobs:
run: |
cp bot_microservice/settings/.env.ci.runtests bot_microservice/settings/.env
docker compose run bot poetry run bash -c "coverage run -m pytest -vv --exitfirst && poetry run coverage report"
#----------------------------------------------
# check dependencies
#----------------------------------------------
- name: Extended checks
continue-on-error: true
run: |
poetry run poetry check
poetry run pip check

View File

@ -37,12 +37,15 @@ lint-typing:
lint-complexity:
flake8 $(PY_TARGET_DIRS)
## Запустить все линтеры
lint: lint-typing lint-complexity check-import-sorting
## Проверить зависимостей
lint-deps:
safety check --full-report && pip-audit
poetry run poetry check
poetry run pip check
poetry run safety check --full-report
poetry run pip-audit
## Запустить все линтеры
lint: lint-typing lint-complexity check-import-sorting lint-deps
## Show help
help:

View File

@ -1,10 +1,9 @@
from fastapi import APIRouter, Request
from settings.config import get_settings
from settings.config import settings
from starlette import status
from starlette.responses import Response
router = APIRouter()
settings = get_settings()
@router.post(

View File

@ -3,7 +3,7 @@ from enum import StrEnum
AUDIO_SEGMENT_DURATION = 120 * 1000
API_PREFIX = "/api"
CHAT_GPT_BASE_URL = "http://chat_service:1338/backend-api/v2/conversation"
CHAT_GPT_BASE_URL = "http://chat_service:8858/backend-api/v2/conversation"
class LogLevelEnum(StrEnum):

View File

@ -8,6 +8,7 @@ from constants import CHAT_GPT_BASE_URL
from core.utils import SpeechToTextService
from httpx import AsyncClient, AsyncHTTPTransport
from loguru import logger
from settings.config import settings
from telegram import Update
from telegram.ext import ContextTypes
@ -33,7 +34,7 @@ async def ask_question(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
chat_gpt_request = {
"conversation_id": str(uuid4()),
"action": "_ask",
"model": "gpt-3.5-turbo",
"model": settings.GPT_MODEL,
"jailbreak": "default",
"meta": {
"id": random.randint(10**18, 10**19 - 1), # noqa: S311

View File

@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Any, cast
from constants import LogLevelEnum
from loguru import logger
from sentry_sdk.integrations.logging import EventHandler
from settings.config import get_settings
from settings.config import settings
if TYPE_CHECKING:
from loguru import Record
@ -14,9 +14,6 @@ else:
Record = dict[str, Any]
settings = get_settings()
class InterceptHandler(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
# Get corresponding Loguru level if it exists

View File

@ -2,9 +2,7 @@ from api.bot.controllers import router as bot_router
from api.system.controllers import router as system_router
from fastapi import APIRouter
from fastapi.responses import ORJSONResponse
from settings.config import get_settings
settings = get_settings()
from settings.config import settings
api_router = APIRouter(
prefix=settings.api_prefix,

View File

@ -47,6 +47,7 @@ class AppSettings(SentrySettings, BaseSettings):
DOMAIN: str = "https://localhost"
URL_PREFIX: str = ""
GPT_MODEL: str = "gpt-3.5-turbo-stream-AItianhuSpace"
# quantity of workers for uvicorn
WORKERS_COUNT: int = 1
# Enable uvicorn reloading
@ -74,3 +75,6 @@ class AppSettings(SentrySettings, BaseSettings):
def get_settings() -> AppSettings:
return AppSettings()
settings = get_settings()

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,69 @@
name: ubuntu-gcc13
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_PASSWORD }}
- name: Build the Docker image to dev
if: github.ref_name == 'dev'
run: |
docker build . -t ${{ secrets.DOCKERHUB_USERNAME }}/freegpt:dev
- 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

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

@ -1,157 +1,89 @@
# FreeGPT WebUI
## Build
```bash
docker build -t balsh_chat_gpt --network=host .
```
# Cpp FreeGPT WebUI
## GPT 3.5/4
<strong>NOT REQUIRE ANY API KEY</strong> ❌🔑
<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.
## Known bugs 🚧
- Stream mode not working properly.
## News 📢
I have created a new version of FreeGPT WebUI using the [ChimeraGPT API](https://chimeragpt.adventblocks.cc/).
<br>
<br>
This free API allows you to use various AI chat models, including <strong>GPT-4, GPT-4-32k, llama-2 and more.</strong> <br>
Check out the project here: [FreeGPT WebUI - Chimera Version](https://github.com/ramonvc/freegpt-webui/tree/chimeragpt-version).
## Project Hosting and Demonstration 🌐🚀
The project is hosted on multiple platforms to be tested and modified.
|Platform|Status|API Key|Free|Repo|Demo|
|--|--|--|--|--|--|
|[replit](https://replit.com/)|![Active](https://img.shields.io/badge/Active-brightgreen)|◼️|☑️|[FreeGPT WebUI](https://replit.com/@ramonvc/freegpt-webui)|[Chat](https://freegpt-webui.ramonvc.repl.co/chat/)
|[hugging face](https://huggingface.co)|![Active](https://img.shields.io/badge/Active-brightgreen)|◼️|☑️|[FreeGPT WebUI](https://huggingface.co/spaces/monra/freegpt-webui/tree/main)|[Chat](https://huggingface.co/spaces/monra/freegpt-webui)
|[replit](https://replit.com/)|![Active](https://img.shields.io/badge/Active-brightgreen)|☑️|☑️|[FreeGPT WebUI - Chimera Version](https://replit.com/@ramonvc/freegpt-webui-chimera)|[Chat](https://freegpt-webui-chimera.ramonvc.repl.co/chat/)
|[hugging face](https://huggingface.co)|![Active](https://img.shields.io/badge/Active-brightgreen)|☑️|☑️|[FreeGPT WebUI - Chimera Version](https://huggingface.co/spaces/monra/freegpt-webui-chimera/tree/main)|[Chat](https://huggingface.co/spaces/monra/freegpt-webui-chimera)
## Note
<p>
FreeGPT is a project that utilizes various free AI conversation API Providers. Each Provider is an API that provides responses generated by different AI models. The source code related to these services is available in <a href="https://github.com/ramonvc/freegpt-webui/tree/main/g4f">G4F folder</a>.
It is important to note that, due to the extensive reach of this project, the free services registered here may receive a significant number of requests, which can result in temporary unavailability or access limitations. Therefore, it is common to encounter these services being offline or unstable.
We recommend that you search for your own Providers and add them to your personal projects to avoid service instability and unavailability. Within the project, in the <a href="https://github.com/ramonvc/freegpt-webui/tree/main/g4f/Provider/Providers">Providers folder</a>, you will find several examples of Providers that have worked in the past or are still functioning. It is easy to follow the logic of these examples to find free GPT services and incorporate the requests into your specific FreeGPT project.
Please note that the choice and integration of additional Providers are the user's responsibility and are not directly related to the FreeGPT project, as the project serves as an example of how to combine the <a href="https://github.com/xtekky/gpt4free">G4F API</a> with a web interface.
</p>
## Table of Contents
- [To-Do List](#to-do-list-%EF%B8%8F)
- [Getting Started](#getting-started-white_check_mark)
- [Cloning the Repository](#cloning-the-repository-inbox_tray)
- [Install Dependencies](#install-dependencies-wrench)
- [Running the Application](#running-the-application-rocket)
- [Docker](#docker-)
- [Prerequisites](#prerequisites)
- [Running the Docker](#running-the-docker)
- [Incorporated Projects](#incorporated-projects-busts_in_silhouette)
- [WebUI](#webui)
- [API FreeGPT](#api-g4f)
- [Star History](#star-history)
- [Legal Notice](#legal-notice)
##
## To-Do List ✔️
- [x] Integrate the free GPT API into the WebUI
- [x] Create Docker support
- [x] Improve the Jailbreak functionality
- [x] Add the GPT-4 model
- [x] Enhance the user interface
- [ ] Check status of API Providers (online/offline)
- [ ] Enable editing and creating Jailbreaks/Roles in the WebUI
- [ ] Refactor web client
## Getting Started :white_check_mark:
To get started with this project, you'll need to clone the repository and have [Python](https://www.python.org/downloads/) installed on your system.
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/ramonvc/freegpt-webui.git
git clone https://github.com/fantasy-peak/cpp-freegpt-webui.git
```
### Install Dependencies :wrench:
Navigate to the project directory:
```
cd freegpt-webui
```
Install the dependencies:
```
pip install -r requirements.txt
```
## Running the Application :rocket:
## Compile And Running the Application :rocket:
To run the application, run the following command:
```
python run.py
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
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:1338
http://127.0.0.1:8858/chat
```
or
```
http://localhost:1338
```
## Docker 🐳
### Prerequisites
Before you start, make sure you have installed [Docker](https://www.docker.com/get-started) on your machine.
### Running the Docker
Pull the Docker image from Docker Hub:
```
docker pull ramonvc/freegpt-webui
docker pull fantasypeak/freegpt:latest
```
Run the application using Docker:
```
docker run -p 1338:1338 ramonvc/freegpt-webui
docker run --net=host -it --name freegpt fantasypeak/freegpt:latest
// OR
docker run -p 8858:8858 -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
```
Access the application in your browser using the URL:
### Call OpenAi Api
```
http://127.0.0.1:1338
// 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
```
or
```
http://localhost:1338
```
When you're done using the application, stop the Docker containers using the following command:
```
docker stop <container-id>
```
## Incorporated Projects :busts_in_silhouette:
I highly recommend visiting and supporting both projects.
### 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.
<br>
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=ramonvc/freegpt-webui&type=Timeline)](https://star-history.com/#ramonvc/freegpt-webui&Timeline)
<br>
## 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

View File

@ -1,2 +0,0 @@
[python: **/server/.py]
[jinja2: **/client/html/**.html]

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

@ -1,26 +0,0 @@
.button {
display: flex;
padding: 8px 12px;
align-items: center;
justify-content: center;
border: 1px solid var(--conversations);
border-radius: var(--border-radius-1);
width: 100%;
background: transparent;
cursor: pointer;
}
.button span {
color: var(--colour-3);
font-size: 0.875rem;
}
.button i::before {
margin-right: 8px;
}
@media screen and (max-width: 990px) {
.button span {
font-size: 0.75rem;
}
}

View File

@ -1,4 +0,0 @@
.buttons {
display: flex;
justify-content: left;
}

View File

@ -1,55 +0,0 @@
.checkbox input {
height: 0;
width: 0;
display: none;
}
.checkbox span {
font-size: 0.875rem;
color: var(--colour-2);
margin-left: 4px;
}
.checkbox label:after {
content: "";
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 5px;
width: 20px;
height: 20px;
background: var(--blur-border);
border-radius: 90px;
transition: 0.33s;
}
.checkbox input + label:after,
.checkbox input:checked + label {
background: var(--colour-3);
}
.checkbox input + label,
.checkbox input:checked + label:after {
background: var(--blur-border);
}
.checkbox input:checked + label:after {
left: calc(100% - 5px - 20px);
}
@media screen and (max-width: 990px) {
.checkbox label {
width: 25px;
height: 15px;
}
.checkbox label:after {
left: 2px;
width: 10px;
height: 10px;
}
.checkbox input:checked + label:after {
left: calc(100% - 2px - 10px);
}
}

View File

@ -1,158 +0,0 @@
.conversation {
width: 60%;
margin: 0px 16px;
display: flex;
flex-direction: column;
}
.conversation #messages {
width: 100%;
display: flex;
flex-direction: column;
overflow: auto;
overflow-wrap: break-word;
padding-bottom: 8px;
}
.conversation .user-input {
max-height: 180px;
margin: 16px 0px;
}
.conversation .user-input input {
font-size: 1rem;
background: none;
border: none;
outline: none;
color: var(--colour-3);
}
.conversation .user-input input::placeholder {
color: var(--user-input);
}
.conversation-title {
color: var(--colour-3);
font-size: 14px;
}
.conversation .user-input textarea {
font-size: 1rem;
width: 100%;
height: 100%;
padding: 12px;
background: none;
border: none;
outline: none;
color: var(--colour-3);
resize: vertical;
max-height: 150px;
min-height: 80px;
}
.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);
}
.box.input-box {
position: relative;
align-items: center;
padding: 8px;
cursor: pointer;
}
#send-button {
position: absolute;
bottom: 25%;
right: 10px;
z-index: 1;
padding: 16px;
}
#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;
}
}
/* scrollbar */
.conversation #messages::-webkit-scrollbar {
width: 4px;
padding: 8px 0px;
}
.conversation #messages::-webkit-scrollbar-track {
background-color: #ffffff00;
}
.conversation #messages::-webkit-scrollbar-thumb {
background-color: #555555;
border-radius: 10px;
}
@media screen and (max-width: 990px) {
.conversation {
width: 100%;
height: 90%;
}
}
@media screen and (max-height: 720px) {
.conversation.box {
height: 70%;
}
.conversation .user-input textarea {
font-size: 0.875rem;
}
}
@media screen and (max-width: 360px) {
.box {
border-radius: 0;
}
.conversation {
margin: 0;
margin-top: 48px;
}
.conversation .user-input {
margin: 2px 0 8px 0;
}
}

View File

@ -1,10 +0,0 @@
.dropdown {
border: 1px solid var(--conversations);
}
@media screen and (max-width: 990px) {
.dropdown {
padding: 4px 8px;
font-size: 0.75rem;
}
}

View File

@ -1,11 +0,0 @@
.field {
display: flex;
align-items: center;
padding: 4px;
}
@media screen and (max-width: 990px) {
.field {
flex-wrap: nowrap;
}
}

View File

@ -1,70 +0,0 @@
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap");
* {
--font-1: "Inter", sans-serif;
--section-gap: 24px;
--border-radius-1: 8px;
margin: 0;
padding: 0;
box-sizing: border-box;
position: relative;
font-family: var(--font-1);
}
.theme-light {
--colour-1: #f5f5f5;
--colour-2: #000000;
--colour-3: #474747;
--colour-4: #949494;
--colour-5: #ebebeb;
--colour-6: #dadada;
--accent: #3a3a3a;
--blur-bg: #ffffff;
--blur-border: #dbdbdb;
--user-input: #282828;
--conversations: #666666;
}
.theme-dark {
--colour-1: #181818;
--colour-2: #ccc;
--colour-3: #dadada;
--colour-4: #f0f0f0;
--colour-5: #181818;
--colour-6: #242424;
--accent: #151718;
--blur-bg: #242627;
--blur-border: #242627;
--user-input: #f5f5f5;
--conversations: #555555;
}
html,
body {
background: var(--colour-1);
color: var(--colour-3);
}
ol,
ul {
padding-left: 20px;
}
.shown {
display: flex !important;
}
a:-webkit-any-link {
color: var(--accent);
}
pre {
white-space: pre-wrap;
}
@media screen and (max-height: 720px) {
:root {
--section-gap: 16px;
}
}

View File

@ -1,68 +0,0 @@
.hljs {
color: #e9e9f4;
background: #28293629;
border-radius: var(--border-radius-1);
border: 1px solid var(--blur-border);
font-size: 15px;
word-wrap: break-word;
white-space: pre-wrap;
}
/* 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: 0.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;
}
.hljs-copy-alert {
clip: rect(0 0 0 0);
clip-path: inset(50%);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}
@media (prefers-reduced-motion) {
.hljs-copy-button {
transition: none;
}
}

View File

@ -1,16 +0,0 @@
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;
}

View File

@ -1,14 +0,0 @@
.main-container {
display: flex;
padding: var(--section-gap);
height: 100vh;
justify-content: center;
box-sizing: border-box;
}
@media screen and (max-width: 360px) {
.main-container {
padding: 0px;
height: 90vh;
}
}

View File

@ -1,27 +0,0 @@
#message-input {
margin-right: 30px;
height: 64px;
}
#message-input::-webkit-scrollbar {
width: 5px;
}
#message-input::-webkit-scrollbar-track {
background: #f1f1f1;
}
#message-input::-webkit-scrollbar-thumb {
background: #c7a2ff;
}
#message-input::-webkit-scrollbar-thumb:hover {
background: #8b3dff;
}
@media screen and (max-width: 360px) {
#message-input {
margin: 0;
}
}

View File

@ -1,65 +0,0 @@
.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 .avatar-container img {
max-width: 48px;
max-height: 48px;
box-shadow: 0.4px 0.5px 0.7px -2px rgba(0, 0, 0, 0.08), 1.1px 1.3px 2px -2px rgba(0, 0, 0, 0.041),
2.7px 3px 4.8px -2px rgba(0, 0, 0, 0.029), 9px 10px 16px -2px rgba(0, 0, 0, 0.022);
}
.message .content {
display: flex;
flex-direction: column;
width: 90%;
gap: 18px;
}
.message .content p,
.message .content li,
.message .content code {
font-size: 1rem;
line-height: 1.3;
}
@media screen and (max-height: 720px) {
.message {
padding: 12px;
gap: 0;
}
.message .content {
margin-left: 8px;
width: 80%;
}
.message .avatar-container img {
max-width: 32px;
max-height: 32px;
}
.message .content,
.message .content p,
.message .content li,
.message .content code {
font-size: 0.875rem;
line-height: 1.3;
}
}

View File

@ -1,10 +0,0 @@
.options-container {
display: flex;
flex-wrap: wrap;
}
@media screen and (max-width: 990px) {
.options-container {
justify-content: space-between;
}
}

View File

@ -1,35 +0,0 @@
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;
}
/* scrollbar */
select.dropdown::-webkit-scrollbar {
width: 4px;
padding: 8px 0px;
}
select.dropdown::-webkit-scrollbar-track {
background-color: #ffffff00;
}
select.dropdown::-webkit-scrollbar-thumb {
background-color: #555555;
border-radius: 10px;
}

View File

@ -1,44 +0,0 @@
.settings-container {
color: var(--colour-2);
margin: 24px 0px 8px 0px;
justify-content: center;
}
.settings-container span {
font-size: 0.875rem;
margin: 0;
}
.settings-container label {
width: 24px;
height: 16px;
}
.settings-container .field {
justify-content: space-between;
}
.settings-container .checkbox input + label,
.settings-container .checkbox input:checked + label:after {
background: var(--colour-1);
}
.settings-container .checkbox input + label:after,
.settings-container .checkbox input:checked + label {
background: var(--colour-3);
}
.settings-container .checkbox label:after {
left: 2px;
width: 10px;
height: 10px;
}
.settings-container .checkbox input:checked + label:after {
left: calc(100% - 2px - 10px);
}
.settings-container .dropdown {
padding: 4px 8px;
font-size: 0.75rem;
}

View File

@ -1,197 +0,0 @@
.sidebar {
max-width: 260px;
padding: var(--section-gap);
flex-shrink: 0;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.sidebar .title {
font-size: 14px;
font-weight: 500;
}
.sidebar .conversation-sidebar {
padding: 8px 12px;
display: flex;
gap: 18px;
align-items: center;
user-select: none;
justify-content: space-between;
}
.sidebar .conversation-sidebar .left {
cursor: pointer;
display: flex;
align-items: center;
gap: 10px;
}
.sidebar i {
color: var(--conversations);
cursor: pointer;
}
.sidebar .top {
display: flex;
flex-direction: column;
overflow: hidden;
gap: 16px;
padding-right: 8px;
}
.sidebar .top:hover {
overflow: auto;
}
.sidebar .info {
padding: 8px 12px 0px 12px;
display: flex;
align-items: center;
justify-content: center;
user-select: none;
background: transparent;
width: 100%;
border: none;
text-decoration: none;
}
.sidebar .info span {
color: var(--conversations);
line-height: 1.5;
font-size: 0.75rem;
}
.sidebar .info i::before {
margin-right: 8px;
}
.sidebar-footer {
width: 100%;
margin-top: 16px;
display: flex;
flex-direction: column;
}
.sidebar-footer button {
cursor: pointer;
user-select: none;
background: transparent;
}
.sidebar.shown {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1000;
}
.sidebar.shown .box {
background-color: #16171a;
width: 80%;
height: 100%;
overflow-y: auto;
}
@keyframes spinner {
to {
transform: rotate(360deg);
}
}
/* scrollbar */
.sidebar .top::-webkit-scrollbar {
width: 4px;
padding: 8px 0px;
}
.sidebar .top::-webkit-scrollbar-track {
background-color: #ffffff00;
}
.sidebar .top::-webkit-scrollbar-thumb {
background-color: #555555;
border-radius: 10px;
}
.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 0.6s linear infinite;
}
.menu-button {
display: none !important;
position: absolute;
z-index: 100000;
top: 0;
left: 0;
margin: 10px;
font-size: 1rem;
cursor: pointer;
width: 30px;
height: 30px;
justify-content: center;
align-items: center;
transition: 0.33s;
}
.menu-button i {
transition: 0.33s;
}
.rotated {
transform: rotate(360deg);
}
.menu-button.rotated {
position: fixed;
top: 10px;
left: 10px;
z-index: 1001;
}
@media screen and (max-width: 990px) {
.sidebar {
display: none;
width: 100%;
max-width: none;
}
.menu-button {
display: flex !important;
}
}
@media (max-width: 990px) {
.sidebar .top {
padding-top: 48px;
}
}
@media (min-width: 768px) {
.sidebar.shown {
position: static;
width: auto;
height: auto;
background-color: transparent;
}
.sidebar.shown .box {
background-color: #16171a;
width: auto;
height: auto;
overflow-y: auto;
}
}

View File

@ -1,38 +0,0 @@
.stop-generating {
position: absolute;
bottom: 128px;
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);
color: var(--colour-3);
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;
}

View File

@ -1,18 +1,821 @@
@import "global.css";
@import "hljs.css";
@import "main.css";
@import "sidebar.css";
@import "conversation.css";
@import "message.css";
@import "stop-generating.css";
@import "typing.css";
@import "checkbox.css";
@import "label.css";
@import "button.css";
@import "buttons.css";
@import "dropdown.css";
@import "field.css";
@import "select.css";
@import "options.css";
@import "settings.css";
@import "message-input.css";
@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

@ -1,15 +0,0 @@
.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;
}

View File

@ -1,135 +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="{{ url_for('bp.static', filename='css/style.css') }}" />
<link
rel="apple-touch-icon"
sizes="180x180"
href="{{ url_for('bp.static', filename='img/apple-touch-icon.png') }}" />
<link
rel="icon"
type="image/png"
sizes="32x32"
href="{{ url_for('bp.static', filename='img/favicon-32x32.png') }}" />
<link
rel="icon"
type="image/png"
sizes="16x16"
href="{{ url_for('bp.static', filename='img/favicon-16x16.png') }}" />
<link rel="manifest" href="{{ url_for('bp.static', filename='img/site.webmanifest') }}" />
<link
rel="stylesheet"
href="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@latest/build/styles/base16/dracula.min.css" />
<title>FreeGPT</title>
</head>
<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="/assets/css/style.css">
<link rel="apple-touch-icon" sizes="180x180" href="/assets/img/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/assets/img/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/assets/img/favicon-16x16.png">
<link rel="manifest" href="/assets/img/site.webmanifest">
<script src="/assets/js/icons.js"></script>
<script src="/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="/assets/img/user.png" alt="User Avatar">`;
const gpt_image = `<img src="/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;
}
<body data-urlprefix="{{ url_prefix}}">
<div class="main-container">
<div class="box sidebar">
<div class="top">
<button class="button" onclick="new_conversation()">
<i class="fa-regular fa-plus"></i>
<span>{{_('New Conversation')}}</span>
</button>
<div class="spinner"></div>
</div>
<div class="sidebar-footer">
<button class="button" onclick="delete_conversations()">
<i class="fa-regular fa-trash"></i>
<span>{{_('Clear Conversations')}}</span>
</button>
<div class="settings-container">
<div class="checkbox field">
<span>{{_('Dark Mode')}}</span>
<input type="checkbox" id="theme-toggler" />
<label for="theme-toggler"></label>
</div>
<div class="field">
<span>{{_('Language')}}</span>
<select
class="dropdown"
id="language"
onchange="changeLanguage(this.value)"></select>
</div>
</div>
<a class="info" href="https://github.com/ramonvc/gptfree-jailbreak-webui" target="_blank">
<i class="fa-brands fa-github"></i>
<span class="conversation-title"> {{_('Version')}}: 0.1.0 </span>
</a>
</div>
</div>
<div class="conversation">
<div class="stop-generating stop-generating-hidden">
<button class="button" id="cancelButton">
<span>{{_('Stop Generating')}}</span>
</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"></textarea>
<div id="send-button">
<i class="fa-regular fa-paper-plane-top"></i>
</div>
</div>
</div>
<div>
<div class="options-container">
<div class="buttons">
<div class="field">
<select class="dropdown" name="model" id="model">
<option value="gpt-3.5-turbo" selected>GPT-3.5</option>
<option value="gpt-3.5-turbo-16k">GPT-3.5-turbo-16k</option>
<option value="gpt-4">GPT-4</option>
</select>
</div>
<div class="field">
<select class="dropdown" name="jailbreak" id="jailbreak">
<option value="default" selected>{{_('Default')}}</option>
<option value="gpt-dan-11.0">{{_('DAN')}}</option>
<option value="gpt-evil">{{_('Evil')}}</option>
</select>
</div>
</div>
<div class="field checkbox">
<input type="checkbox" id="switch" />
<label for="switch"></label>
<span>{{_('Web Access')}}</span>
</div>
</div>
</div>
</div>
</div>
<div class="menu-button">
<i class="fa-solid fa-bars"></i>
</div>
#message-input {
margin-right: 30px;
height: 80px;
}
<!-- scripts -->
<script>
window.conversation_id = "{{ chat_id }}";
</script>
<script src="{{ url_for('bp.static', filename='js/icons.js') }}"></script>
<script src="{{ url_for('bp.static', filename='js/chat.js') }}" defer></script>
<script src="https://cdn.jsdelivr.net/npm/markdown-it@latest/dist/markdown-it.min.js"></script>
<script src="{{ url_for('bp.static', filename='js/highlight.min.js') }}"></script>
<script src="{{ url_for('bp.static', filename='js/highlightjs-copy.min.js') }}"></script>
<script src="{{ url_for('bp.static', filename='js/theme-toggler.js') }}"></script>
<script src="{{ url_for('bp.static', filename='js/sidebar-toggler.js') }}"></script>
<script src="{{ url_for('bp.static', filename='js/change-language.js') }}"></script>
</body>
#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="/assets/js/highlight.min.js"></script>
<script src="/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.6 <br>
Release: 2023-09-06<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.

Before

Width:  |  Height:  |  Size: 9.3 KiB

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 536 B

After

Width:  |  Height:  |  Size: 499 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View File

@ -1,47 +0,0 @@
document.addEventListener('DOMContentLoaded', fetchLanguages);
async function fetchLanguages() {
try {
const [languagesResponse, currentLanguageResponse] = await Promise.all([
fetch(`${url_prefix}/get-languages`),
fetch(`${url_prefix}/get-locale`)
]);
const languages = await languagesResponse.json();
const currentLanguage = await currentLanguageResponse.text();
const languageSelect = document.getElementById('language');
languages.forEach(lang => {
const option = document.createElement('option');
option.value = lang;
option.textContent = lang;
languageSelect.appendChild(option);
});
const savedLanguage = localStorage.getItem("language") || currentLanguage;
setLanguageOnPageLoad(savedLanguage);
} catch (error) {
console.error("Failed to fetch languages or current language");
}
}
function setLanguageOnPageLoad(language) {
document.getElementById("language").value = language;
}
function changeLanguage(lang) {
fetch(`${url_prefix}/change-language`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ language: lang }),
}).then((response) => {
if (response.ok) {
localStorage.setItem("language", lang);
location.reload();
} else {
console.error("Failed to change language");
}
});
}

View File

@ -1,84 +1,105 @@
const query = (obj) =>
Object.keys(obj)
.map((k) => encodeURIComponent(k) + "=" + encodeURIComponent(obj[k]))
.join("&");
const url_prefix = document.querySelector("body").getAttribute("data-urlprefix");
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 stop_generating = document.querySelector(`.stop_generating`);
const send_button = document.querySelector(`#send-button`);
const user_image = `<img src="${url_prefix}/assets/img/user.png" alt="User Avatar">`;
const gpt_image = `<img src="${url_prefix}/assets/img/gpt.png" alt="GPT Avatar">`;
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);
window.scrollTo(0, 0);
});
message_input.addEventListener("focus", () => {
document.documentElement.scrollTop = document.documentElement.scrollHeight;
document.documentElement.scrollTop = document.documentElement.scrollHeight;
});
const delete_conversations = async () => {
localStorage.clear();
await new_conversation();
localStorage.clear();
await new_conversation();
};
const handle_ask = async () => {
message_input.style.height = `80px`;
window.scrollTo(0, 0);
let message = message_input.value;
message_input.style.height = `80px`;
message_input.focus();
if (message.length > 0) {
message_input.value = ``;
message_input.dispatchEvent(new Event("input"));
await ask_gpt(message);
}
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`);
stop_generating.classList.add(`stop_generating-hiding`);
setTimeout(() => {
stop_generating.classList.remove(`stop-generating-hiding`);
stop_generating.classList.add(`stop-generating-hidden`);
}, 300);
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 = ``;
try {
message_input.value = ``;
message_input.innerHTML = ``;
message_input.innerText = ``;
add_conversation(window.conversation_id, message.substr(0, 16));
window.scrollTo(0, 0);
window.controller = new AbortController();
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();
jailbreak = document.getElementById("jailbreak");
model = document.getElementById("model");
prompt_lock = true;
window.text = ``;
window.token = message_id();
stop_generating.classList.remove(`stop-generating-hidden`);
stop_generating.classList.remove(`stop_generating-hidden`);
add_user_message_box(message);
message_box.scrollTop = message_box.scrollHeight;
window.scrollTo(0, 0);
await new Promise((r) => setTimeout(r, 500));
window.scrollTo(0, 0);
message_box.innerHTML += `
message_box.innerHTML += `
<div class="message">
<div class="avatar-container">
${gpt_image}
<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>
@ -86,423 +107,493 @@ const ask_gpt = async (message) => {
</div>
`;
message_box.scrollTop = message_box.scrollHeight;
window.scrollTo(0, 0);
await new Promise((r) => setTimeout(r, 1000));
window.scrollTo(0, 0);
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(`${url_prefix}/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 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();
const reader = response.body.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
while (true) {
const { value, done } = await reader.read();
if (done) break;
chunk = decodeUnicode(new TextDecoder().decode(value));
chunk = new TextDecoder().decode(value);
if (
chunk.includes(`<form id="challenge-form" action="${url_prefix}/backend-api/v2/conversation?`)
) {
chunk = `cloudflare token expired, please refresh the page.`;
}
if (
chunk.includes(
`<form id="challenge-form" action="/backend-api/v2/conversation?`
)
) {
chunk = `cloudflare token expired, please refresh the page.`;
}
text += chunk;
text += chunk;
document.getElementById(`gpt_${window.token}`).innerHTML = markdown.render(text);
document.querySelectorAll(`code`).forEach((el) => {
hljs.highlightElement(el);
});
// const objects = chunk.match(/({.+?})/g);
window.scrollTo(0, 0);
message_box.scrollTo({ top: message_box.scrollHeight, behavior: "auto" });
}
// try { if (JSON.parse(objects[0]).success === false) throw new Error(JSON.parse(objects[0]).error) } catch (e) {}
// 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 occurred, please reload / refresh cache and try again.";
}
// objects.forEach((object) => {
// console.log(object)
// try { text += h2a(JSON.parse(object).content) } catch(t) { console.log(t); throw new Error(t)}
// });
add_message(window.conversation_id, "user", message);
add_message(window.conversation_id, "assistant", text);
document.getElementById(`gpt_${window.token}`).innerHTML =
markdown.render(text);
document.querySelectorAll(`code`).forEach((el) => {
hljs.highlightElement(el);
});
message_box.scrollTop = message_box.scrollHeight;
await remove_cancel_button();
prompt_lock = false;
window.scrollTo(0, 0);
message_box.scrollTo({ top: message_box.scrollHeight, behavior: "auto" });
}
await load_conversations(20, 0);
window.scrollTo(0, 0);
} catch (e) {
add_message(window.conversation_id, "user", message);
// 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.";
}
message_box.scrollTop = message_box.scrollHeight;
await remove_cancel_button();
prompt_lock = false;
add_message(window.conversation_id, "user", message, token);
add_message(window.conversation_id, "assistant", text, token);
await load_conversations(20, 0);
message_box.scrollTop = message_box.scrollHeight;
await remove_cancel_button();
prompt_lock = false;
console.log(e);
await load_conversations(20, 0);
window.scrollTo(0, 0);
} catch (e) {
add_message(window.conversation_id, "user", message, token);
let cursorDiv = document.getElementById(`cursor`);
if (cursorDiv) cursorDiv.parentNode.removeChild(cursorDiv);
message_box.scrollTop = message_box.scrollHeight;
await remove_cancel_button();
prompt_lock = false;
if (e.name != `AbortError`) {
let error_message = `oops ! something went wrong, please try again / reload. [stacktrace in console]`;
await load_conversations(20, 0);
document.getElementById(`gpt_${window.token}`).innerHTML = error_message;
add_message(window.conversation_id, "assistant", error_message);
} else {
document.getElementById(`gpt_${window.token}`).innerHTML += ` [aborted]`;
add_message(window.conversation_id, "assistant", text + ` [aborted]`);
}
console.log(e);
window.scrollTo(0, 0);
}
};
let cursorDiv = document.getElementById(`cursor`);
if (cursorDiv) cursorDiv.parentNode.removeChild(cursorDiv);
const add_user_message_box = (message) => {
const messageDiv = createElement("div", { classNames: ["message"] });
const avatarContainer = createElement("div", { classNames: ["avatar-container"], innerHTML: user_image });
const contentDiv = createElement("div", {
classNames: ["content"],
id: `user_${token}`,
textContent: message,
});
if (e.name != `AbortError`) {
let error_message = `oops ! something went wrong, please try again / reload. [stacktrace in console]`;
messageDiv.append(avatarContainer, contentDiv);
message_box.appendChild(messageDiv);
};
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);
}
const decodeUnicode = (str) => {
return str.replace(/\\u([a-fA-F0-9]{4})/g, function (match, grp) {
return String.fromCharCode(parseInt(grp, 16));
});
window.scrollTo(0, 0);
}
};
const clear_conversations = async () => {
const elements = box_conversations.childNodes;
let index = elements.length;
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);
}
}
}
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`);
let messages = message_box.getElementsByTagName(`div`);
while (messages.length > 0) {
message_box.removeChild(messages[0]);
}
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}`);
localStorage.removeItem(`conversation:${conversation_id}`);
if (window.conversation_id == conversation_id) {
await new_conversation();
}
const conversation = document.getElementById(`convo-${conversation_id}`);
conversation.remove();
await load_conversations(20, 0, true);
if (window.conversation_id == conversation_id) {
await new_conversation();
}
await load_conversations(20, 0, true);
};
const set_conversation = async (conversation_id) => {
history.pushState({}, null, `${url_prefix}/chat/${conversation_id}`);
window.conversation_id = 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);
await clear_conversation();
await load_conversation(conversation_id);
await load_conversations(20, 0, true);
};
const new_conversation = async () => {
history.pushState({}, null, `${url_prefix}/chat/`);
window.conversation_id = uuid();
history.pushState({}, null, `{{chat_path}}/`);
window.conversation_id = uuid();
await clear_conversation();
await load_conversations(20, 0, true);
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);
let conversation = await JSON.parse(
localStorage.getItem(`conversation:${conversation_id}`)
);
console.log(conversation, conversation_id);
for (item of conversation.items) {
if (is_assistant(item.role)) {
message_box.innerHTML += load_gpt_message_box(item.content);
} else {
message_box.innerHTML += load_user_message_box(item.content);
}
}
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 load_user_message_box = (content) => {
const messageDiv = createElement("div", { classNames: ["message"] });
const avatarContainer = createElement("div", { classNames: ["avatar-container"], innerHTML: user_image });
const contentDiv = createElement("div", { classNames: ["content"] });
const preElement = document.createElement("pre");
preElement.textContent = content;
contentDiv.appendChild(preElement);
messageDiv.append(avatarContainer, contentDiv);
return messageDiv.outerHTML;
};
const load_gpt_message_box = (content) => {
return `
for (item of conversation.items) {
message_box.innerHTML += `
<div class="message">
<div class="avatar-container">
${gpt_image}
<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>
<div class="content">
${markdown.render(content)}
${
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>
`;
};
}
const is_assistant = (role) => {
return role == "assistant";
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}`));
return conversation.items;
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: [],
})
);
}
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) => {
before_adding = JSON.parse(localStorage.getItem(`conversation:${conversation_id}`));
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,
});
before_adding.items.push({
role: role,
content: content,
token: token,
});
localStorage.setItem(`conversation:${conversation_id}`, JSON.stringify(before_adding)); // update conversation
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);
//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));
}
}
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();
//if (loader === undefined) spinner.parentNode.removeChild(spinner)
await clear_conversations();
for (conversation of conversations) {
box_conversations.innerHTML += `
<div class="conversation-sidebar">
<div class="left" onclick="set_conversation('${conversation.id}')">
<i class="fa-regular fa-comments"></i>
<span class="conversation-title">${conversation.title}</span>
</div>
<i onclick="delete_conversation('${conversation.id}')" class="fa-regular fa-trash"></i>
</div>
`;
}
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.querySelectorAll(`code`).forEach((el) => {
hljs.highlightElement(el);
});
};
document.getElementById(`cancelButton`).addEventListener(`click`, async () => {
window.controller.abort();
console.log(`aborted ${window.conversation_id}`);
window.controller.abort();
console.log(`aborted ${window.conversation_id}`);
});
function h2a(str1) {
var hex = str1.toString();
var str = "";
var hex = str1.toString();
var str = "";
for (var n = 0; n < hex.length; n += 2) {
str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
}
for (var n = 0; n < hex.length; n += 2) {
str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
}
return str;
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);
});
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);
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();
return BigInt(`0b${unix}${random_bytes}`).toString();
};
window.onload = async () => {
load_settings_localstorage();
load_settings_localstorage();
conversations = 0;
for (let i = 0; i < localStorage.length; i++) {
if (localStorage.key(i).startsWith("conversation:")) {
conversations += 1;
}
}
conversations = 0;
for (let i = 0; i < localStorage.length; i++) {
if (localStorage.key(i).startsWith("conversation:")) {
conversations += 1;
}
}
if (conversations == 0) localStorage.clear();
if (conversations == 0) localStorage.clear();
await setTimeout(() => {
load_conversations(20, 0);
}, 1);
await setTimeout(() => {
load_conversations(20, 0);
}, 1);
if (!window.location.href.endsWith(`#`)) {
if (/\/chat\/.+/.test(window.location.href.slice(url_prefix.length))) {
await load_conversation(window.conversation_id);
}
}
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;
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";
}
});
if (evt.key === "Enter" && !evt.shiftKey) {
evt.preventDefault();
await handle_ask();
}
});
send_button.addEventListener(`click`, async () => {
console.log("clicked send");
if (prompt_lock) return;
await handle_ask();
});
send_button.addEventListener("click", async (event) => {
event.preventDefault();
if (prompt_lock) return;
message_input.blur();
await handle_ask();
});
register_settings_localstorage();
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");
}
})
);
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");
}
}
});
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");
}
}
});
};
function clearTextarea(textarea) {
textarea.style.removeProperty("height");
textarea.style.height = `${textarea.scrollHeight + 4}px`;
if (textarea.value.trim() === "" && textarea.value.includes("\n")) {
textarea.value = "";
}
// 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);
};
}
function createElement(tag, { classNames, id, innerHTML, textContent } = {}) {
const el = document.createElement(tag);
if (classNames) {
el.classList.add(...classNames);
}
if (id) {
el.id = id;
}
if (innerHTML) {
el.innerHTML = innerHTML;
}
if (textContent) {
const preElement = document.createElement("pre");
preElement.textContent = textContent;
el.appendChild(preElement);
}
return el;
}
document.onload = setTheme();

View File

@ -1,34 +0,0 @@
const sidebar = document.querySelector(".sidebar");
const menuButton = document.querySelector(".menu-button");
function toggleSidebar(event) {
if (sidebar.classList.contains("shown")) {
hideSidebar(event.target);
} else {
showSidebar(event.target);
}
window.scrollTo(0, 0);
}
function showSidebar(target) {
sidebar.classList.add("shown");
target.classList.add("rotated");
document.body.style.overflow = "hidden";
}
function hideSidebar(target) {
sidebar.classList.remove("shown");
target.classList.remove("rotated");
document.body.style.overflow = "auto";
}
menuButton.addEventListener("click", toggleSidebar);
document.body.addEventListener('click', function(event) {
if (event.target.matches('.conversation-title')) {
const menuButtonStyle = window.getComputedStyle(menuButton);
if (menuButtonStyle.display !== 'none') {
hideSidebar(menuButton);
}
}
});

View File

@ -1,22 +0,0 @@
var switch_theme_toggler = document.getElementById("theme-toggler");
switch_theme_toggler.addEventListener("change", toggleTheme);
function setTheme(themeName) {
localStorage.setItem("theme", themeName);
document.documentElement.className = themeName;
}
function toggleTheme() {
var currentTheme = localStorage.getItem("theme");
var newTheme = currentTheme === "theme-dark" ? "theme-light" : "theme-dark";
setTheme(newTheme);
switch_theme_toggler.checked = newTheme === "theme-dark";
}
(function () {
var currentTheme = localStorage.getItem("theme") || "theme-dark";
setTheme(currentTheme);
switch_theme_toggler.checked = currentTheme === "theme-dark";
})();

View File

@ -1,8 +0,0 @@
{
"site_config": {
"host": "0.0.0.0",
"port": 1338,
"debug": false
},
"url_prefix": "/gpt"
}

View File

@ -1,38 +0,0 @@
version: "3.9"
networks:
chat_gpt_network:
name: "chat_gpt_network"
services:
chat-gpt-caddy:
image: caddy:2.7.4
container_name: "chat_gpt_caddy"
restart: unless-stopped
networks:
- chat_gpt_network
environment:
- TZ=Europe/Moscow
ports:
- "8081:8080"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- /etc/localtime:/etc/localtime:ro
chat-gpt:
image: balsh_chat_gpt:latest #ramonvc/freegpt-webui:latest
container_name: "chat_gpt"
build:
context: .
dockerfile: Dockerfile
hostname: "chat_gpt"
networks:
- chat_gpt_network
volumes:
- ./client:/client
depends_on:
- chat-gpt-caddy
expose:
- "1338"
restart: unless-stopped

View File

@ -1,19 +0,0 @@
import os
from typing import get_type_hints
url = None
model = None
supports_stream = False
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
return
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,41 +0,0 @@
import os
from typing import get_type_hints
import requests
url = "https://aiservice.vercel.app/api/chat/answer"
model = ["gpt-3.5-turbo"]
supports_stream = False
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
base = ""
for message in messages:
base += "%s: %s\n" % (message["role"], message["content"])
base += "assistant:"
headers = {
"accept": "*/*",
"content-type": "text/plain;charset=UTF-8",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"Referer": "https://aiservice.vercel.app/chat",
}
data = {"input": base}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
_json = response.json()
yield _json["data"]
else:
print(f"Error Occurred::{response.status_code}")
return None
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,46 +0,0 @@
import json
import os
from typing import get_type_hints
import requests
url = "https://hteyun.com"
model = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-16k-0613",
"gpt-3.5-turbo-0613",
]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, temperature: float = 0.7, **kwargs):
headers = {
"Content-Type": "application/json",
}
data = {
"model": model,
"temperature": 0.7,
"presence_penalty": 0,
"messages": messages,
}
response = requests.post(url + "/api/chat-stream", json=data, stream=True)
if stream:
for chunk in response.iter_content(chunk_size=None):
chunk = chunk.decode("utf-8")
if chunk.strip():
message = json.loads(chunk)["choices"][0]["message"]["content"]
yield message
else:
message = response.json()["choices"][0]["message"]["content"]
yield message
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,96 +0,0 @@
import hashlib
import json
import os
import time
import uuid
from datetime import datetime
from typing import Dict, get_type_hints
import requests
from g4f.typing import sha256
url: str = "https://ai.ls"
model: str = "gpt-3.5-turbo"
supports_stream = True
needs_auth = False
working = True
class Utils:
def hash(json_data: Dict[str, str]) -> sha256:
base_string: str = "%s:%s:%s:%s" % (
json_data["t"],
json_data["m"],
"WI,2rU#_r:r~aF4aJ36[.Z(/8Rv93Rf",
len(json_data["m"]),
)
return hashlib.sha256(base_string.encode()).hexdigest()
def format_timestamp(timestamp: int) -> str:
e = timestamp
n = e % 10
r = n + 1 if n % 2 == 0 else n
return str(e - n + r)
def _create_completion(model: str, messages: list, temperature: float = 0.6, stream: bool = False, **kwargs):
headers = {
"authority": "api.caipacity.com",
"accept": "*/*",
"accept-language": "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",
"authorization": "Bearer free",
"client-id": str(uuid.uuid4()),
"client-v": "0.1.249",
"content-type": "application/json",
"origin": "https://ai.ls",
"referer": "https://ai.ls/",
"sec-ch-ua": '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
}
timestamp = Utils.format_timestamp(int(time.time() * 1000))
sig = {
"d": datetime.now().strftime("%Y-%m-%d"),
"t": timestamp,
"s": Utils.hash({"t": timestamp, "m": messages[-1]["content"]}),
}
json_data = json.dumps(
separators=(",", ":"),
obj={
"model": "gpt-3.5-turbo",
"temperature": 0.6,
"stream": True,
"messages": messages,
}
| sig,
)
response = requests.post(
"https://api.caipacity.com/v1/chat/completions",
headers=headers,
data=json_data,
stream=True,
)
for token in response.iter_lines():
if b"content" in token:
completion_chunk = json.loads(token.decode().replace("data: ", ""))
token = completion_chunk["choices"][0]["delta"].get("content")
if token != None:
yield token
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,87 +0,0 @@
import json
import os
import random
import re
from typing import get_type_hints
import browser_cookie3
import requests
url = "https://bard.google.com"
model = ["Palm2"]
supports_stream = False
needs_auth = True
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
psid = {cookie.name: cookie.value for cookie in browser_cookie3.chrome(domain_name=".google.com")}["__Secure-1PSID"]
formatted = "\n".join(["%s: %s" % (message["role"], message["content"]) for message in messages])
prompt = f"{formatted}\nAssistant:"
proxy = kwargs.get("proxy", False)
if proxy == False:
print("warning!, you did not give a proxy, a lot of countries are banned from Google Bard, so it may not work")
snlm0e = None
conversation_id = None
response_id = None
choice_id = None
client = requests.Session()
client.proxies = {"http": f"http://{proxy}", "https": f"http://{proxy}"} if proxy else None
client.headers = {
"authority": "bard.google.com",
"content-type": "application/x-www-form-urlencoded;charset=UTF-8",
"origin": "https://bard.google.com",
"referer": "https://bard.google.com/",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36",
"x-same-domain": "1",
"cookie": f"__Secure-1PSID={psid}",
}
snlm0e = (
re.search(r"SNlM0e\":\"(.*?)\"", client.get("https://bard.google.com/").text).group(1) if not snlm0e else snlm0e
)
params = {
"bl": "boq_assistant-bard-web-server_20230326.21_p0",
"_reqid": random.randint(1111, 9999),
"rt": "c",
}
data = {
"at": snlm0e,
"f.req": json.dumps(
[
None,
json.dumps([[prompt], None, [conversation_id, response_id, choice_id]]),
]
),
}
intents = ".".join(["assistant", "lamda", "BardFrontendService"])
response = client.post(
f"https://bard.google.com/_/BardChatUi/data/{intents}/StreamGenerate",
data=data,
params=params,
)
chat_data = json.loads(response.content.splitlines()[3])[0][2]
if chat_data:
json_chat_data = json.loads(chat_data)
yield json_chat_data[0][0]
else:
yield "error"
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,64 +0,0 @@
import json
import os
from typing import get_type_hints
import requests
url = "https://openai-proxy-api.vercel.app/v1/"
model = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-0613",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-16k-0613",
"gpt-4",
]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
headers = {
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.58",
"Referer": "https://chat.ylokh.xyz/",
"Origin": "https://chat.ylokh.xyz",
"Connection": "keep-alive",
}
json_data = {
"messages": messages,
"temperature": 1.0,
"model": model,
"stream": stream,
}
response = requests.post(
"https://openai-proxy-api.vercel.app/v1/chat/completions",
headers=headers,
json=json_data,
stream=True,
)
for token in response.iter_lines():
decoded = token.decode("utf-8")
if decoded.startswith("data: "):
data_str = decoded.replace("data: ", "")
data = json.loads(data_str)
if "choices" in data and "delta" in data["choices"][0]:
delta = data["choices"][0]["delta"]
content = delta.get("content", "")
finish_reason = delta.get("finish_reason", "")
if finish_reason == "stop":
break
if content:
yield content
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,355 +0,0 @@
import asyncio
import json
import os
import random
import ssl
import uuid
from typing import get_type_hints
import aiohttp
import certifi
import requests
url = "https://bing.com/chat"
model = ["gpt-4"]
supports_stream = True
needs_auth = False
ssl_context = ssl.create_default_context()
ssl_context.load_verify_locations(certifi.where())
class optionsSets:
optionSet: dict = {"tone": str, "optionsSets": list}
jailbreak: dict = {
"optionsSets": [
"saharasugg",
"enablenewsfc",
"clgalileo",
"gencontentv3",
"nlu_direct_response_filter",
"deepleo",
"disable_emoji_spoken_text",
"responsible_ai_policy_235",
"enablemm",
"h3precise"
# "harmonyv3",
"dtappid",
"cricinfo",
"cricinfov2",
"dv3sugg",
"nojbfedge",
]
}
class Defaults:
delimiter = "\x1e"
ip_address = f"13.{random.randint(104, 107)}.{random.randint(0, 255)}.{random.randint(0, 255)}"
allowedMessageTypes = [
"Chat",
"Disengaged",
"AdsQuery",
"SemanticSerp",
"GenerateContentQuery",
"SearchQuery",
"ActionRequest",
"Context",
"Progress",
"AdsQuery",
"SemanticSerp",
]
sliceIds = [
# "222dtappid",
# "225cricinfo",
# "224locals0"
"winmuid3tf",
"osbsdusgreccf",
"ttstmout",
"crchatrev",
"winlongmsgtf",
"ctrlworkpay",
"norespwtf",
"tempcacheread",
"temptacache",
"505scss0",
"508jbcars0",
"515enbotdets0",
"5082tsports",
"515vaoprvs",
"424dagslnv1s0",
"kcimgattcf",
"427startpms0",
]
location = {
"locale": "en-US",
"market": "en-US",
"region": "US",
"locationHints": [
{
"country": "United States",
"state": "California",
"city": "Los Angeles",
"timezoneoffset": 8,
"countryConfidence": 8,
"Center": {"Latitude": 34.0536909, "Longitude": -118.242766},
"RegionType": 2,
"SourceType": 1,
}
],
}
def _format(msg: dict) -> str:
return json.dumps(msg, ensure_ascii=False) + Defaults.delimiter
async def create_conversation():
for _ in range(5):
create = requests.get(
"https://www.bing.com/turing/conversation/create",
headers={
"authority": "edgeservices.bing.com",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"accept-language": "en-US,en;q=0.9",
"cache-control": "max-age=0",
"sec-ch-ua": '"Chromium";v="110", "Not A(Brand";v="24", "Microsoft Edge";v="110"',
"sec-ch-ua-arch": '"x86"',
"sec-ch-ua-bitness": '"64"',
"sec-ch-ua-full-version": '"110.0.1587.69"',
"sec-ch-ua-full-version-list": '"Chromium";v="110.0.5481.192", "Not A(Brand";v="24.0.0.0", "Microsoft Edge";v="110.0.1587.69"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-model": '""',
"sec-ch-ua-platform": '"Windows"',
"sec-ch-ua-platform-version": '"15.0.0"',
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "none",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.69",
"x-edge-shopping-flag": "1",
"x-forwarded-for": Defaults.ip_address,
},
)
conversationId = create.json().get("conversationId")
clientId = create.json().get("clientId")
conversationSignature = create.json().get("conversationSignature")
if not conversationId or not clientId or not conversationSignature and _ == 4:
raise Exception("Failed to create conversation.")
return conversationId, clientId, conversationSignature
async def stream_generate(
prompt: str,
mode: optionsSets.optionSet = optionsSets.jailbreak,
context: bool or str = False,
):
timeout = aiohttp.ClientTimeout(total=900)
session = aiohttp.ClientSession(timeout=timeout)
conversationId, clientId, conversationSignature = await create_conversation()
wss = await session.ws_connect(
"wss://sydney.bing.com/sydney/ChatHub",
ssl=ssl_context,
autoping=False,
headers={
"accept": "application/json",
"accept-language": "en-US,en;q=0.9",
"content-type": "application/json",
"sec-ch-ua": '"Not_A Brand";v="99", "Microsoft Edge";v="110", "Chromium";v="110"',
"sec-ch-ua-arch": '"x86"',
"sec-ch-ua-bitness": '"64"',
"sec-ch-ua-full-version": '"109.0.1518.78"',
"sec-ch-ua-full-version-list": '"Chromium";v="110.0.5481.192", "Not A(Brand";v="24.0.0.0", "Microsoft Edge";v="110.0.1587.69"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-model": "",
"sec-ch-ua-platform": '"Windows"',
"sec-ch-ua-platform-version": '"15.0.0"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-ms-client-request-id": str(uuid.uuid4()),
"x-ms-useragent": "azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32",
"Referer": "https://www.bing.com/search?q=Bing+AI&showconv=1&FORM=hpcodx",
"Referrer-Policy": "origin-when-cross-origin",
"x-forwarded-for": Defaults.ip_address,
},
)
await wss.send_str(_format({"protocol": "json", "version": 1}))
await wss.receive(timeout=900)
struct = {
"arguments": [
{
**mode,
"source": "cib",
"allowedMessageTypes": Defaults.allowedMessageTypes,
"sliceIds": Defaults.sliceIds,
"traceId": os.urandom(16).hex(),
"isStartOfSession": True,
"message": Defaults.location
| {
"author": "user",
"inputMethod": "Keyboard",
"text": prompt,
"messageType": "Chat",
},
"conversationSignature": conversationSignature,
"participant": {"id": clientId},
"conversationId": conversationId,
}
],
"invocationId": "0",
"target": "chat",
"type": 4,
}
if context:
struct["arguments"][0]["previousMessages"] = [
{
"author": "user",
"description": context,
"contextType": "WebPage",
"messageType": "Context",
"messageId": "discover-web--page-ping-mriduna-----",
}
]
await wss.send_str(_format(struct))
final = False
draw = False
resp_txt = ""
result_text = ""
resp_txt_no_link = ""
cache_text = ""
while not final:
msg = await wss.receive(timeout=900)
objects = msg.data.split(Defaults.delimiter)
for obj in objects:
if obj is None or not obj:
continue
response = json.loads(obj)
if response.get("type") == 1 and response["arguments"][0].get(
"messages",
):
if not draw:
if (response["arguments"][0]["messages"][0]["contentOrigin"] != "Apology") and not draw:
resp_txt = result_text + response["arguments"][0]["messages"][0]["adaptiveCards"][0]["body"][
0
].get("text", "")
resp_txt_no_link = result_text + response["arguments"][0]["messages"][0].get("text", "")
if response["arguments"][0]["messages"][0].get(
"messageType",
):
resp_txt = (
resp_txt
+ response["arguments"][0]["messages"][0]["adaptiveCards"][0]["body"][0]["inlines"][
0
].get("text")
+ "\n"
)
result_text = (
result_text
+ response["arguments"][0]["messages"][0]["adaptiveCards"][0]["body"][0]["inlines"][
0
].get("text")
+ "\n"
)
if cache_text.endswith(" "):
final = True
if wss and not wss.closed:
await wss.close()
if session and not session.closed:
await session.close()
yield (resp_txt.replace(cache_text, ""))
cache_text = resp_txt
elif response.get("type") == 2:
if response["item"]["result"].get("error"):
if wss and not wss.closed:
await wss.close()
if session and not session.closed:
await session.close()
raise Exception(f"{response['item']['result']['value']}: {response['item']['result']['message']}")
if draw:
cache = response["item"]["messages"][1]["adaptiveCards"][0]["body"][0]["text"]
response["item"]["messages"][1]["adaptiveCards"][0]["body"][0]["text"] = cache + resp_txt
if response["item"]["messages"][-1]["contentOrigin"] == "Apology" and resp_txt:
response["item"]["messages"][-1]["text"] = resp_txt_no_link
response["item"]["messages"][-1]["adaptiveCards"][0]["body"][0]["text"] = resp_txt
# print('Preserved the message from being deleted', file=sys.stderr)
final = True
if wss and not wss.closed:
await wss.close()
if session and not session.closed:
await session.close()
def run(generator):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
gen = generator.__aiter__()
while True:
try:
next_val = loop.run_until_complete(gen.__anext__())
yield next_val
except StopAsyncIteration:
break
# print('Done')
def convert(messages):
context = ""
for message in messages:
context += "[%s](#message)\n%s\n\n" % (message["role"], message["content"])
return context
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
if len(messages) < 2:
prompt = messages[0]["content"]
context = False
else:
prompt = messages[-1]["content"]
context = convert(messages[:-1])
response = run(stream_generate(prompt, optionsSets.jailbreak, context))
for token in response:
yield (token)
# print('Done')
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,58 +0,0 @@
import json
import os
from typing import get_type_hints
import requests
url = "https://v.chatfree.cc"
model = ["gpt-3.5-turbo", "gpt-3.5-turbo-16k"]
supports_stream = False
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
headers = {
"authority": "chat.dfehub.com",
"accept": "*/*",
"accept-language": "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",
"content-type": "application/json",
"origin": "https://v.chatfree.cc",
"referer": "https://v.chatfree.cc/",
"sec-ch-ua": '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"macOS"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"x-requested-with": "XMLHttpRequest",
}
json_data = {
"messages": messages,
"stream": True,
"model": model,
"temperature": 0.5,
"presence_penalty": 0,
"frequency_penalty": 0,
"top_p": 1,
}
response = requests.post(
"https://v.chatfree.cc/api/openai/v1/chat/completions",
headers=headers,
json=json_data,
)
for chunk in response.iter_lines():
if b"content" in chunk:
data = json.loads(chunk.decode().split("data: ")[1])
yield (data["choices"][0]["delta"]["content"])
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,60 +0,0 @@
import os
import re
from typing import get_type_hints
import requests
url = "https://chatgpt.ai/gpt-4/"
model = ["gpt-4"]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
chat = ""
for message in messages:
chat += "%s: %s\n" % (message["role"], message["content"])
chat += "assistant: "
response = requests.get("https://chatgpt.ai/")
nonce, post_id, _, bot_id = re.findall(
r'data-nonce="(.*)"\n data-post-id="(.*)"\n data-url="(.*)"\n data-bot-id="(.*)"\n data-width',
response.text,
)[0]
headers = {
"authority": "chatgpt.ai",
"accept": "*/*",
"accept-language": "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",
"cache-control": "no-cache",
"origin": "https://chatgpt.ai",
"pragma": "no-cache",
"referer": "https://chatgpt.ai/gpt-4/",
"sec-ch-ua": '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
}
data = {
"_wpnonce": nonce,
"post_id": post_id,
"url": "https://chatgpt.ai/gpt-4",
"action": "wpaicg_chat_shortcode_message",
"message": chat,
"bot_id": bot_id,
}
response = requests.post("https://chatgpt.ai/wp-admin/admin-ajax.php", headers=headers, data=data)
yield (response.json()["data"])
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,113 +0,0 @@
import base64
import os
import re
from typing import get_type_hints
import requests
url = "https://chatgptlogin.ac"
model = ["gpt-3.5-turbo"]
supports_stream = False
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
def get_nonce():
res = requests.get(
"https://chatgptlogin.ac/use-chatgpt-free/",
headers={
"Referer": "https://chatgptlogin.ac/use-chatgpt-free/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
},
)
src = re.search(
r'class="mwai-chat mwai-chatgpt">.*<span>Send</span></button></div></div></div> <script defer src="(.*?)">',
res.text,
).group(1)
decoded_string = base64.b64decode(src.split(",")[-1]).decode("utf-8")
return re.search(r"let restNonce = '(.*?)';", decoded_string).group(1)
def transform(messages: list) -> list:
def html_encode(string: str) -> str:
table = {
'"': "&quot;",
"'": "&#39;",
"&": "&amp;",
">": "&gt;",
"<": "&lt;",
"\n": "<br>",
"\t": "&nbsp;&nbsp;&nbsp;&nbsp;",
" ": "&nbsp;",
}
for key in table:
string = string.replace(key, table[key])
return string
return [
{
"id": os.urandom(6).hex(),
"role": message["role"],
"content": message["content"],
"who": "AI: " if message["role"] == "assistant" else "User: ",
"html": html_encode(message["content"]),
}
for message in messages
]
headers = {
"authority": "chatgptlogin.ac",
"accept": "*/*",
"accept-language": "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",
"content-type": "application/json",
"origin": "https://chatgptlogin.ac",
"referer": "https://chatgptlogin.ac/use-chatgpt-free/",
"sec-ch-ua": '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"x-wp-nonce": get_nonce(),
}
conversation = transform(messages)
json_data = {
"env": "chatbot",
"session": "N/A",
"prompt": "Converse as if you were an AI assistant. Be friendly, creative.",
"context": "Converse as if you were an AI assistant. Be friendly, creative.",
"messages": conversation,
"newMessage": messages[-1]["content"],
"userName": '<div class="mwai-name-text">User:</div>',
"aiName": '<div class="mwai-name-text">AI:</div>',
"model": "gpt-3.5-turbo",
"temperature": 0.8,
"maxTokens": 1024,
"maxResults": 1,
"apiKey": "",
"service": "openai",
"embeddingsIndex": "",
"stop": "",
"clientId": os.urandom(6).hex(),
}
response = requests.post(
"https://chatgptlogin.ac/wp-json/ai-chatbot/v1/chat",
headers=headers,
json=json_data,
)
return response.json()["reply"]
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,48 +0,0 @@
import hashlib
import json
import os
import random
from typing import get_type_hints
import requests
url = "https://deepai.org"
model = ["gpt-3.5-turbo"]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
def md5(text: str) -> str:
return hashlib.md5(text.encode()).hexdigest()[::-1]
def get_api_key(user_agent: str) -> str:
part1 = str(random.randint(0, 10**11))
part2 = md5(user_agent + md5(user_agent + md5(user_agent + part1 + "x")))
return f"tryit-{part1}-{part2}"
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
headers = {"api-key": get_api_key(user_agent), "user-agent": user_agent}
files = {"chat_style": (None, "chat"), "chatHistory": (None, json.dumps(messages))}
r = requests.post(
"https://api.deepai.org/chat_response",
headers=headers,
files=files,
stream=True,
)
for chunk in r.iter_content(chunk_size=None):
r.raise_for_status()
yield chunk.decode()
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,66 +0,0 @@
import json
import os
from typing import get_type_hints
import requests
url = "https://free.easychat.work"
model = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-16k-0613",
"gpt-3.5-turbo-0613",
]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
headers = {
"authority": "free.easychat.work",
"accept": "text/event-stream",
"accept-language": "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",
"content-type": "application/json",
"endpoint": "",
"origin": "https://free.easychat.work",
"plugins": "0",
"referer": "https://free.easychat.work/",
"sec-ch-ua": '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"macOS"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"usesearch": "false",
"x-requested-with": "XMLHttpRequest",
}
json_data = {
"messages": messages,
"stream": True,
"model": model,
"temperature": 0.5,
"presence_penalty": 0,
"frequency_penalty": 0,
"top_p": 1,
}
response = requests.post(
"https://free.easychat.work/api/openai/v1/chat/completions",
headers=headers,
json=json_data,
)
for chunk in response.iter_lines():
if b"content" in chunk:
data = json.loads(chunk.decode().split("data: ")[1])
yield (data["choices"][0]["delta"]["content"])
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,46 +0,0 @@
import json
import os
from typing import get_type_hints
import requests
url = "https://gpt4.ezchat.top"
model = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-16k-0613",
"gpt-3.5-turbo-0613",
]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, temperature: float = 0.7, **kwargs):
headers = {
"Content-Type": "application/json",
}
data = {
"model": model,
"temperature": 0.7,
"presence_penalty": 0,
"messages": messages,
}
response = requests.post(url + "/api/openai/v1/chat/completions", json=data, stream=True)
if stream:
for chunk in response.iter_content(chunk_size=None):
chunk = chunk.decode("utf-8")
if chunk.strip():
message = json.loads(chunk)["choices"][0]["message"]["content"]
yield message
else:
message = response.json()["choices"][0]["message"]["content"]
yield message
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,59 +0,0 @@
import json
import os
from typing import get_type_hints
import requests
url = "https://ai.fakeopen.com/v1/"
model = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-0613",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-16k-0613",
]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
headers = {
"Content-Type": "application/json",
"accept": "text/event-stream",
"Cache-Control": "no-cache",
"Proxy-Connection": "keep-alive",
"Authorization": f"Bearer {os.environ.get('FAKE_OPEN_KEY', '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')}",
}
json_data = {
"messages": messages,
"temperature": 1.0,
"model": model,
"stream": stream,
}
response = requests.post(
"https://ai.fakeopen.com/v1/chat/completions",
headers=headers,
json=json_data,
stream=True,
)
for token in response.iter_lines():
decoded = token.decode("utf-8")
if decoded == "[DONE]":
break
if decoded.startswith("data: "):
data_str = decoded.replace("data: ", "")
if data_str != "[DONE]":
data = json.loads(data_str)
if "choices" in data and "delta" in data["choices"][0] and "content" in data["choices"][0]["delta"]:
yield data["choices"][0]["delta"]["content"]
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,41 +0,0 @@
import json
import os
from typing import get_type_hints
import requests
url = "https://forefront.com"
model = ["gpt-3.5-turbo"]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
json_data = {
"text": messages[-1]["content"],
"action": "noauth",
"id": "",
"parentId": "",
"workspaceId": "",
"messagePersona": "607e41fe-95be-497e-8e97-010a59b2e2c0",
"model": "gpt-4",
"messages": messages[:-1] if len(messages) > 1 else [],
"internetMode": "auto",
}
response = requests.post(
"https://streaming.tenant-forefront-default.knative.chi.coreweave.com/free-chat",
json=json_data,
stream=True,
)
for token in response.iter_lines():
if b"delta" in token:
token = json.loads(token.decode().split("data: ")[1])["delta"]
yield (token)
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,68 +0,0 @@
import json
import os
import uuid
from typing import get_type_hints
import requests
from Crypto.Cipher import AES
url = "https://chat.getgpt.world/"
model = ["gpt-3.5-turbo"]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
def encrypt(e):
t = os.urandom(8).hex().encode("utf-8")
n = os.urandom(8).hex().encode("utf-8")
r = e.encode("utf-8")
cipher = AES.new(t, AES.MODE_CBC, n)
ciphertext = cipher.encrypt(pad_data(r))
return ciphertext.hex() + t.decode("utf-8") + n.decode("utf-8")
def pad_data(data: bytes) -> bytes:
block_size = AES.block_size
padding_size = block_size - len(data) % block_size
padding = bytes([padding_size] * padding_size)
return data + padding
headers = {
"Content-Type": "application/json",
"Referer": "https://chat.getgpt.world/",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
}
data = json.dumps(
{
"messages": messages,
"frequency_penalty": kwargs.get("frequency_penalty", 0),
"max_tokens": kwargs.get("max_tokens", 4000),
"model": "gpt-3.5-turbo",
"presence_penalty": kwargs.get("presence_penalty", 0),
"temperature": kwargs.get("temperature", 1),
"top_p": kwargs.get("top_p", 1),
"stream": True,
"uuid": str(uuid.uuid4()),
}
)
res = requests.post(
"https://chat.getgpt.world/api/chat/stream",
headers=headers,
json={"signature": encrypt(data)},
stream=True,
)
for line in res.iter_lines():
if b"content" in line:
line_json = json.loads(line.decode("utf-8").split("data: ")[1])
yield (line_json["choices"][0]["delta"]["content"])
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,32 +0,0 @@
import os
from typing import get_type_hints
import requests
url = "https://gpt4.xunika.uk/"
model = ["gpt-3.5-turbo-16k", "gpt-3.5-turbo-0613"]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, temperature: float = 0.7, **kwargs):
headers = {
"Content-Type": "application/json",
}
data = {
"model": model,
"temperature": 0.7,
"presence_penalty": 0,
"messages": messages,
}
response = requests.post(url + "/api/openai/v1/chat/completions", json=data, stream=True)
yield response.json()["choices"][0]["message"]["content"]
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,114 +0,0 @@
import os
from json import loads
from typing import get_type_hints
from uuid import uuid4
from requests import Session
url = "https://gpt-gm.h2o.ai"
model = ["falcon-40b", "falcon-7b", "llama-13b"]
supports_stream = True
needs_auth = False
models = {
"falcon-7b": "h2oai/h2ogpt-gm-oasst1-en-2048-falcon-7b-v3",
"falcon-40b": "h2oai/h2ogpt-gm-oasst1-en-2048-falcon-40b-v1",
"llama-13b": "h2oai/h2ogpt-gm-oasst1-en-2048-open-llama-13b",
}
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
conversation = "instruction: this is a conversation beween, a user and an AI assistant, respond to the latest message, referring to the conversation if needed\n"
for message in messages:
conversation += "%s: %s\n" % (message["role"], message["content"])
conversation += "assistant:"
client = Session()
client.headers = {
"authority": "gpt-gm.h2o.ai",
"origin": "https://gpt-gm.h2o.ai",
"referer": "https://gpt-gm.h2o.ai/",
"sec-ch-ua": '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "same-origin",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
}
client.get("https://gpt-gm.h2o.ai/")
response = client.post(
"https://gpt-gm.h2o.ai/settings",
data={
"ethicsModalAccepted": "true",
"shareConversationsWithModelAuthors": "true",
"ethicsModalAcceptedAt": "",
"activeModel": "h2oai/h2ogpt-gm-oasst1-en-2048-falcon-40b-v1",
"searchEnabled": "true",
},
)
headers = {
"authority": "gpt-gm.h2o.ai",
"accept": "*/*",
"accept-language": "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",
"origin": "https://gpt-gm.h2o.ai",
"referer": "https://gpt-gm.h2o.ai/",
"sec-ch-ua": '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
}
json_data = {"model": models[model]}
response = client.post("https://gpt-gm.h2o.ai/conversation", headers=headers, json=json_data)
conversationId = response.json()["conversationId"]
completion = client.post(
f"https://gpt-gm.h2o.ai/conversation/{conversationId}",
stream=True,
json={
"inputs": conversation,
"parameters": {
"temperature": kwargs.get("temperature", 0.4),
"truncate": kwargs.get("truncate", 2048),
"max_new_tokens": kwargs.get("max_new_tokens", 1024),
"do_sample": kwargs.get("do_sample", True),
"repetition_penalty": kwargs.get("repetition_penalty", 1.2),
"return_full_text": kwargs.get("return_full_text", False),
},
"stream": True,
"options": {
"id": kwargs.get("id", str(uuid4())),
"response_id": kwargs.get("response_id", str(uuid4())),
"is_retry": False,
"use_cache": False,
"web_search_id": "",
},
},
)
for line in completion.iter_lines():
if b"data" in line:
line = loads(line.decode("utf-8").replace("data:", ""))
token = line["token"]["text"]
if token == "<|endoftext|>":
break
else:
yield (token)
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,60 +0,0 @@
import os
from typing import get_type_hints
import requests
url = "https://liaobots.com"
model = ["gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-4"]
supports_stream = True
needs_auth = True
working = False
models = {
"gpt-4": {"id": "gpt-4", "name": "GPT-4", "maxLength": 24000, "tokenLimit": 8000},
"gpt-3.5-turbo": {
"id": "gpt-3.5-turbo",
"name": "GPT-3.5",
"maxLength": 12000,
"tokenLimit": 4000,
},
"gpt-3.5-turbo-16k": {
"id": "gpt-3.5-turbo-16k",
"name": "GPT-3.5-16k",
"maxLength": 48000,
"tokenLimit": 16000,
},
}
def _create_completion(model: str, messages: list, stream: bool, chatId: str, **kwargs):
print(kwargs)
headers = {
"authority": "liaobots.com",
"content-type": "application/json",
"origin": "https://liaobots.com",
"referer": "https://liaobots.com/",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
"x-auth-code": "qlcUMVn1KLMhd",
}
json_data = {
"conversationId": chatId,
"model": models[model],
"messages": messages,
"key": "",
"prompt": "You are ChatGPT, a large language model trained by OpenAI. Follow the user's instructions carefully. Respond using markdown.",
}
response = requests.post("https://liaobots.com/api/chat", headers=headers, json=json_data, stream=True)
for token in response.iter_content(chunk_size=2046):
yield (token.decode("utf-8"))
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,50 +0,0 @@
import json
import os
from typing import get_type_hints
import requests
url = "http://supertest.lockchat.app"
model = ["gpt-4", "gpt-3.5-turbo"]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, temperature: float = 0.7, **kwargs):
payload = {
"temperature": 0.7,
"messages": messages,
"model": model,
"stream": True,
}
headers = {
"user-agent": "ChatX/39 CFNetwork/1408.0.4 Darwin/22.5.0",
}
response = requests.post(
"http://supertest.lockchat.app/v1/chat/completions",
json=payload,
headers=headers,
stream=True,
)
for token in response.iter_lines():
if b"The model: `gpt-4` does not exist" in token:
print("error, retrying...")
_create_completion(
model=model,
messages=messages,
stream=stream,
temperature=temperature,
**kwargs,
)
if b"content" in token:
token = json.loads(token.decode("utf-8").split("data: ")[1])["choices"][0]["delta"].get("content")
if token:
yield (token)
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,26 +0,0 @@
import os
from typing import get_type_hints
import requests
url = "https://mishalsgpt.vercel.app"
model = ["gpt-3.5-turbo-16k-0613", "gpt-3.5-turbo"]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
headers = {
"Content-Type": "application/json",
}
data = {"model": model, "temperature": 0.7, "messages": messages}
response = requests.post(url + "/api/openai/v1/chat/completions", headers=headers, json=data, stream=True)
yield response.json()["choices"][0]["message"]["content"]
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,37 +0,0 @@
import json
import os
import subprocess
from typing import get_type_hints
url = "https://phind.com"
model = ["gpt-4"]
supports_stream = True
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
path = os.path.dirname(os.path.realpath(__file__))
config = json.dumps({"model": model, "messages": messages}, separators=(",", ":"))
cmd = ["python", f"{path}/helpers/phind.py", config]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b""):
if b"<title>Just a moment...</title>" in line:
os.system("clear" if os.name == "posix" else "cls")
yield "Clouflare error, please try again..."
os._exit(0)
else:
if b"ping - 2023-" in line:
continue
yield line.decode("cp1251") # [:-1]
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,29 +0,0 @@
import json
import os
import subprocess
from typing import get_type_hints
url = "https://theb.ai"
model = ["gpt-3.5-turbo"]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
path = os.path.dirname(os.path.realpath(__file__))
config = json.dumps({"messages": messages, "model": model}, separators=(",", ":"))
cmd = ["python3", f"{path}/helpers/theb.py", config]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b""):
yield line.decode("utf-8")
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,514 +0,0 @@
import base64
import json
import os
import queue
import threading
from typing import get_type_hints
import execjs
from curl_cffi import requests
url = "https://play.vercel.ai"
supports_stream = True
needs_auth = False
models = {
"claude-instant-v1": "anthropic:claude-instant-v1",
"claude-v1": "anthropic:claude-v1",
"alpaca-7b": "replicate:replicate/alpaca-7b",
"stablelm-tuned-alpha-7b": "replicate:stability-ai/stablelm-tuned-alpha-7b",
"bloom": "huggingface:bigscience/bloom",
"bloomz": "huggingface:bigscience/bloomz",
"flan-t5-xxl": "huggingface:google/flan-t5-xxl",
"flan-ul2": "huggingface:google/flan-ul2",
"gpt-neox-20b": "huggingface:EleutherAI/gpt-neox-20b",
"oasst-sft-4-pythia-12b-epoch-3.5": "huggingface:OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5",
"santacoder": "huggingface:bigcode/santacoder",
"command-medium-nightly": "cohere:command-medium-nightly",
"command-xlarge-nightly": "cohere:command-xlarge-nightly",
"code-cushman-001": "openai:code-cushman-001",
"code-davinci-002": "openai:code-davinci-002",
"gpt-3.5-turbo": "openai:gpt-3.5-turbo",
"text-ada-001": "openai:text-ada-001",
"text-babbage-001": "openai:text-babbage-001",
"text-curie-001": "openai:text-curie-001",
"text-davinci-002": "openai:text-davinci-002",
"text-davinci-003": "openai:text-davinci-003",
}
model = models.keys()
vercel_models = {
"anthropic:claude-instant-v1": {
"id": "anthropic:claude-instant-v1",
"provider": "anthropic",
"providerHumanName": "Anthropic",
"makerHumanName": "Anthropic",
"minBillingTier": "hobby",
"parameters": {
"temperature": {"value": 1, "range": [0, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0.1, 1]},
"topK": {"value": 1, "range": [1, 500]},
"presencePenalty": {"value": 1, "range": [0, 1]},
"frequencyPenalty": {"value": 1, "range": [0, 1]},
"stopSequences": {"value": ["\n\nHuman:"], "range": []},
},
"name": "claude-instant-v1",
},
"anthropic:claude-v1": {
"id": "anthropic:claude-v1",
"provider": "anthropic",
"providerHumanName": "Anthropic",
"makerHumanName": "Anthropic",
"minBillingTier": "hobby",
"parameters": {
"temperature": {"value": 1, "range": [0, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0.1, 1]},
"topK": {"value": 1, "range": [1, 500]},
"presencePenalty": {"value": 1, "range": [0, 1]},
"frequencyPenalty": {"value": 1, "range": [0, 1]},
"stopSequences": {"value": ["\n\nHuman:"], "range": []},
},
"name": "claude-v1",
},
"replicate:replicate/alpaca-7b": {
"id": "replicate:replicate/alpaca-7b",
"provider": "replicate",
"providerHumanName": "Replicate",
"makerHumanName": "Stanford",
"parameters": {
"temperature": {"value": 0.75, "range": [0.01, 5]},
"maximumLength": {"value": 200, "range": [50, 512]},
"topP": {"value": 0.95, "range": [0.01, 1]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"repetitionPenalty": {"value": 1.1765, "range": [0.01, 5]},
"stopSequences": {"value": [], "range": []},
},
"version": "2014ee1247354f2e81c0b3650d71ca715bc1e610189855f134c30ecb841fae21",
"name": "alpaca-7b",
},
"replicate:stability-ai/stablelm-tuned-alpha-7b": {
"id": "replicate:stability-ai/stablelm-tuned-alpha-7b",
"provider": "replicate",
"makerHumanName": "StabilityAI",
"providerHumanName": "Replicate",
"parameters": {
"temperature": {"value": 0.75, "range": [0.01, 5]},
"maximumLength": {"value": 200, "range": [50, 512]},
"topP": {"value": 0.95, "range": [0.01, 1]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"repetitionPenalty": {"value": 1.1765, "range": [0.01, 5]},
"stopSequences": {"value": [], "range": []},
},
"version": "4a9a32b4fd86c2d047f1d271fa93972683ec6ef1cf82f402bd021f267330b50b",
"name": "stablelm-tuned-alpha-7b",
},
"huggingface:bigscience/bloom": {
"id": "huggingface:bigscience/bloom",
"provider": "huggingface",
"providerHumanName": "HuggingFace",
"makerHumanName": "BigScience",
"instructions": "Do NOT talk to Bloom as an entity, it's not a chatbot but a webpage/blog/article completion model. For the best results: mimic a few words of a webpage similar to the content you want to generate. Start a sentence as if YOU were writing a blog, webpage, math post, coding article and Bloom will generate a coherent follow-up.",
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 0.95, "range": [0.01, 0.99]},
"topK": {"value": 4, "range": [1, 500]},
"repetitionPenalty": {"value": 1.03, "range": [0.1, 2]},
},
"name": "bloom",
},
"huggingface:bigscience/bloomz": {
"id": "huggingface:bigscience/bloomz",
"provider": "huggingface",
"providerHumanName": "HuggingFace",
"makerHumanName": "BigScience",
"instructions": 'We recommend using the model to perform tasks expressed in natural language. For example, given the prompt "Translate to English: Je t\'aime.", the model will most likely answer "I love you.".',
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 0.95, "range": [0.01, 0.99]},
"topK": {"value": 4, "range": [1, 500]},
"repetitionPenalty": {"value": 1.03, "range": [0.1, 2]},
},
"name": "bloomz",
},
"huggingface:google/flan-t5-xxl": {
"id": "huggingface:google/flan-t5-xxl",
"provider": "huggingface",
"makerHumanName": "Google",
"providerHumanName": "HuggingFace",
"name": "flan-t5-xxl",
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 0.95, "range": [0.01, 0.99]},
"topK": {"value": 4, "range": [1, 500]},
"repetitionPenalty": {"value": 1.03, "range": [0.1, 2]},
},
},
"huggingface:google/flan-ul2": {
"id": "huggingface:google/flan-ul2",
"provider": "huggingface",
"providerHumanName": "HuggingFace",
"makerHumanName": "Google",
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 0.95, "range": [0.01, 0.99]},
"topK": {"value": 4, "range": [1, 500]},
"repetitionPenalty": {"value": 1.03, "range": [0.1, 2]},
},
"name": "flan-ul2",
},
"huggingface:EleutherAI/gpt-neox-20b": {
"id": "huggingface:EleutherAI/gpt-neox-20b",
"provider": "huggingface",
"providerHumanName": "HuggingFace",
"makerHumanName": "EleutherAI",
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 0.95, "range": [0.01, 0.99]},
"topK": {"value": 4, "range": [1, 500]},
"repetitionPenalty": {"value": 1.03, "range": [0.1, 2]},
"stopSequences": {"value": [], "range": []},
},
"name": "gpt-neox-20b",
},
"huggingface:OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5": {
"id": "huggingface:OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5",
"provider": "huggingface",
"providerHumanName": "HuggingFace",
"makerHumanName": "OpenAssistant",
"parameters": {
"maximumLength": {"value": 200, "range": [50, 1024]},
"typicalP": {"value": 0.2, "range": [0.1, 0.99]},
"repetitionPenalty": {"value": 1, "range": [0.1, 2]},
},
"name": "oasst-sft-4-pythia-12b-epoch-3.5",
},
"huggingface:bigcode/santacoder": {
"id": "huggingface:bigcode/santacoder",
"provider": "huggingface",
"providerHumanName": "HuggingFace",
"makerHumanName": "BigCode",
"instructions": 'The model was trained on GitHub code. As such it is not an instruction model and commands like "Write a function that computes the square root." do not work well. You should phrase commands like they occur in source code such as comments (e.g. # the following function computes the sqrt) or write a function signature and docstring and let the model complete the function body.',
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 0.95, "range": [0.01, 0.99]},
"topK": {"value": 4, "range": [1, 500]},
"repetitionPenalty": {"value": 1.03, "range": [0.1, 2]},
},
"name": "santacoder",
},
"cohere:command-medium-nightly": {
"id": "cohere:command-medium-nightly",
"provider": "cohere",
"providerHumanName": "Cohere",
"makerHumanName": "Cohere",
"name": "command-medium-nightly",
"parameters": {
"temperature": {"value": 0.9, "range": [0, 2]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0, 1]},
"topK": {"value": 0, "range": [0, 500]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"stopSequences": {"value": [], "range": []},
},
},
"cohere:command-xlarge-nightly": {
"id": "cohere:command-xlarge-nightly",
"provider": "cohere",
"providerHumanName": "Cohere",
"makerHumanName": "Cohere",
"name": "command-xlarge-nightly",
"parameters": {
"temperature": {"value": 0.9, "range": [0, 2]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0, 1]},
"topK": {"value": 0, "range": [0, 500]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"stopSequences": {"value": [], "range": []},
},
},
"openai:gpt-4": {
"id": "openai:gpt-4",
"provider": "openai",
"providerHumanName": "OpenAI",
"makerHumanName": "OpenAI",
"name": "gpt-4",
"minBillingTier": "pro",
"parameters": {
"temperature": {"value": 0.7, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0.1, 1]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"stopSequences": {"value": [], "range": []},
},
},
"openai:code-cushman-001": {
"id": "openai:code-cushman-001",
"provider": "openai",
"providerHumanName": "OpenAI",
"makerHumanName": "OpenAI",
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0.1, 1]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"stopSequences": {"value": [], "range": []},
},
"name": "code-cushman-001",
},
"openai:code-davinci-002": {
"id": "openai:code-davinci-002",
"provider": "openai",
"providerHumanName": "OpenAI",
"makerHumanName": "OpenAI",
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0.1, 1]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"stopSequences": {"value": [], "range": []},
},
"name": "code-davinci-002",
},
"openai:gpt-3.5-turbo": {
"id": "openai:gpt-3.5-turbo",
"provider": "openai",
"providerHumanName": "OpenAI",
"makerHumanName": "OpenAI",
"parameters": {
"temperature": {"value": 0.7, "range": [0, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0.1, 1]},
"topK": {"value": 1, "range": [1, 500]},
"presencePenalty": {"value": 1, "range": [0, 1]},
"frequencyPenalty": {"value": 1, "range": [0, 1]},
"stopSequences": {"value": [], "range": []},
},
"name": "gpt-3.5-turbo",
},
"openai:text-ada-001": {
"id": "openai:text-ada-001",
"provider": "openai",
"providerHumanName": "OpenAI",
"makerHumanName": "OpenAI",
"name": "text-ada-001",
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0.1, 1]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"stopSequences": {"value": [], "range": []},
},
},
"openai:text-babbage-001": {
"id": "openai:text-babbage-001",
"provider": "openai",
"providerHumanName": "OpenAI",
"makerHumanName": "OpenAI",
"name": "text-babbage-001",
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0.1, 1]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"stopSequences": {"value": [], "range": []},
},
},
"openai:text-curie-001": {
"id": "openai:text-curie-001",
"provider": "openai",
"providerHumanName": "OpenAI",
"makerHumanName": "OpenAI",
"name": "text-curie-001",
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0.1, 1]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"stopSequences": {"value": [], "range": []},
},
},
"openai:text-davinci-002": {
"id": "openai:text-davinci-002",
"provider": "openai",
"providerHumanName": "OpenAI",
"makerHumanName": "OpenAI",
"name": "text-davinci-002",
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0.1, 1]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"stopSequences": {"value": [], "range": []},
},
},
"openai:text-davinci-003": {
"id": "openai:text-davinci-003",
"provider": "openai",
"providerHumanName": "OpenAI",
"makerHumanName": "OpenAI",
"name": "text-davinci-003",
"parameters": {
"temperature": {"value": 0.5, "range": [0.1, 1]},
"maximumLength": {"value": 200, "range": [50, 1024]},
"topP": {"value": 1, "range": [0.1, 1]},
"presencePenalty": {"value": 0, "range": [0, 1]},
"frequencyPenalty": {"value": 0, "range": [0, 1]},
"stopSequences": {"value": [], "range": []},
},
},
}
# based on https://github.com/ading2210/vercel-llm-api // modified
class Client:
def __init__(self):
self.session = requests.Session()
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.5",
"Te": "trailers",
"Upgrade-Insecure-Requests": "1",
}
self.session.headers.update(self.headers)
def get_token(self):
b64 = self.session.get("https://sdk.vercel.ai/openai.jpeg").text
data = json.loads(base64.b64decode(b64))
code = "const globalThis = {data: `sentinel`}; function token() {return (%s)(%s)}" % (data["c"], data["a"])
token_string = json.dumps(
separators=(",", ":"),
obj={"r": execjs.compile(code).call("token"), "t": data["t"]},
)
return base64.b64encode(token_string.encode()).decode()
def get_default_params(self, model_id):
return {key: param["value"] for key, param in vercel_models[model_id]["parameters"].items()}
def generate(self, model_id: str, prompt: str, params: dict = {}):
if not ":" in model_id:
model_id = models[model_id]
defaults = self.get_default_params(model_id)
payload = (
defaults
| params
| {
"prompt": prompt,
"model": model_id,
}
)
headers = self.headers | {
"Accept-Encoding": "gzip, deflate, br",
"Custom-Encoding": self.get_token(),
"Host": "sdk.vercel.ai",
"Origin": "https://sdk.vercel.ai",
"Referrer": "https://sdk.vercel.ai",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
}
chunks_queue = queue.Queue()
error = None
response = None
def callback(data):
chunks_queue.put(data.decode())
def request_thread():
nonlocal response, error
for _ in range(3):
try:
response = self.session.post(
"https://sdk.vercel.ai/api/generate",
json=payload,
headers=headers,
content_callback=callback,
)
response.raise_for_status()
except Exception as e:
if _ == 2:
error = e
else:
continue
thread = threading.Thread(target=request_thread, daemon=True)
thread.start()
text = ""
index = 0
while True:
try:
chunk = chunks_queue.get(block=True, timeout=0.1)
except queue.Empty:
if error:
raise error
elif response:
break
else:
continue
text += chunk
lines = text.split("\n")
if len(lines) - 1 > index:
new = lines[index:-1]
for word in new:
yield json.loads(word)
index = len(lines) - 1
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
yield "Vercel is currently not working."
return
conversation = "This is a conversation between a human and a language model, respond to the last message accordingly, referring to the past history of messages if needed.\n"
for message in messages:
conversation += "%s: %s\n" % (message["role"], message["content"])
conversation += "assistant: "
completion = Client().generate(model, conversation)
for token in completion:
yield token
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,39 +0,0 @@
import os
from typing import get_type_hints
import requests
url = "https://api.gptplus.one"
model = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-16k-0613",
"gpt-3.5-turbo-0613",
]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, temperature: float = 0.7, **kwargs):
headers = {
"Content-Type": "application/json",
"Accept": "*/*",
"Accept-Language": "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,ja;q=0.6,zh-TW;q=0.5,zh;q=0.4",
}
data = {
"messages": messages,
"model": model,
}
response = requests.post("https://api.gptplus.one/chat-process", json=data, stream=True)
print(response)
for token in response.iter_content(chunk_size=None):
yield (token.decode("utf-8"))
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,72 +0,0 @@
import json
import os
import random
import string
import time
from typing import get_type_hints
import requests
url = "https://wewordle.org/gptapi/v1/android/turbo"
model = ["gpt-3.5-turbo"]
supports_stream = False
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
base = ""
for message in messages:
base += "%s: %s\n" % (message["role"], message["content"])
base += "assistant:"
# randomize user id and app id
_user_id = "".join(random.choices(f"{string.ascii_lowercase}{string.digits}", k=16))
_app_id = "".join(random.choices(f"{string.ascii_lowercase}{string.digits}", k=31))
# make current date with format utc
_request_date = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
headers = {
"accept": "*/*",
"pragma": "no-cache",
"Content-Type": "application/json",
"Connection": "keep-alive",
}
data = {
"user": _user_id,
"messages": [{"role": "user", "content": base}],
"subscriber": {
"originalPurchaseDate": None,
"originalApplicationVersion": None,
"allPurchaseDatesMillis": {},
"entitlements": {"active": {}, "all": {}},
"allPurchaseDates": {},
"allExpirationDatesMillis": {},
"allExpirationDates": {},
"originalAppUserId": f"$RCAnonymousID:{_app_id}",
"latestExpirationDate": None,
"requestDate": _request_date,
"latestExpirationDateMillis": None,
"nonSubscriptionTransactions": [],
"originalPurchaseDateMillis": None,
"managementURL": None,
"allPurchasedProductIdentifiers": [],
"firstSeen": _request_date,
"activeSubscriptions": [],
},
}
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
_json = response.json()
if "message" in _json:
message_content = _json["message"]["content"]
message_content = message_content.replace("**assistant:** ", "")
yield message_content
else:
print(f"Error Occurred::{response.status_code}")
return None
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,46 +0,0 @@
import json
import os
from typing import get_type_hints
import requests
url = "https://xiaor.eu.org"
model = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-16k-0613",
"gpt-3.5-turbo-0613",
]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, temperature: float = 0.7, **kwargs):
headers = {
"Content-Type": "application/json",
}
data = {
"model": model,
"temperature": 0.7,
"presence_penalty": 0,
"messages": messages,
}
response = requests.post(url + "/p1/v1/chat/completions", json=data, stream=True)
if stream:
for chunk in response.iter_content(chunk_size=None):
chunk = chunk.decode("utf-8")
if chunk.strip():
message = json.loads(chunk)["choices"][0]["message"]["content"]
yield message
else:
message = response.json()["choices"][0]["message"]["content"]
yield message
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,20 +0,0 @@
import json
import os
import subprocess
url = "https://you.com"
model = "gpt-3.5-turbo"
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
path = os.path.dirname(os.path.realpath(__file__))
config = json.dumps({"messages": messages}, separators=(",", ":"))
cmd = ["python3", f"{path}/helpers/you.py", config]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b""):
yield line.decode("utf-8") # [:-1]

View File

@ -1,45 +0,0 @@
import os
from typing import get_type_hints
import requests
url = "https://chat9.yqcloud.top/"
model = [
"gpt-3.5-turbo",
]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, chatId: str, **kwargs):
headers = {
"authority": "api.aichatos.cloud",
"origin": "https://chat9.yqcloud.top",
"referer": "https://chat9.yqcloud.top/",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
}
json_data = {
"prompt": str(messages),
"userId": f"#/chat/{chatId}",
"network": True,
"apikey": "",
"system": "",
"withoutContext": False,
}
response = requests.post(
"https://api.aichatos.cloud/api/generateStream",
headers=headers,
json=json_data,
stream=True,
)
for token in response.iter_content(chunk_size=2046):
yield (token.decode("utf-8"))
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,63 +0,0 @@
import os
from typing import get_type_hints
import requests
url = "https://gptleg.zeabur.app"
model = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-0301",
"gpt-3.5-turbo-16k",
"gpt-4",
"gpt-4-0613",
]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
headers = {
"Authority": "chat.dfehub.com",
"Content-Type": "application/json",
"Method": "POST",
"Path": "/api/openai/v1/chat/completions",
"Scheme": "https",
"Accept": "text/event-stream",
"Accept-Language": "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6,zh;q=0.5",
"Content-Type": "application/json",
"Origin": "https://gptleg.zeabur.app",
"Referer": "https://gptleg.zeabur.app/",
"Sec-Ch-Ua": '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
"Sec-Ch-Ua-Mobile": "?0",
"Sec-Ch-Ua-Platform": '"Windows"',
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
}
data = {
"model": model,
"temperature": 0.7,
"max_tokens": "16000",
"presence_penalty": 0,
"messages": messages,
}
response = requests.post(
url + "/api/openai/v1/chat/completions",
headers=headers,
json=data,
stream=stream,
)
yield response.json()["choices"][0]["message"]["content"]
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,53 +0,0 @@
import json
import sys
from re import findall
from curl_cffi import requests
config = json.loads(sys.argv[1])
prompt = config["messages"][-1]["content"]
headers = {
"authority": "api.gptplus.one",
"accept": "application/json, text/plain, */*",
"accept-language": "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,ja;q=0.6,zh-TW;q=0.5,zh;q=0.4",
"content-type": "application/octet-stream",
"origin": "https://ai.gptforlove.com/",
"referer": "https://ai.gptforlove.com/",
"sec-ch-ua": '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"macOS"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36",
}
json_data = {"prompt": prompt, "options": {}}
def format(chunk):
try:
completion_chunk = findall(r'content":"(.*)"},"fin', chunk.decode())[0]
print(completion_chunk, flush=True, end="")
except Exception:
print(f"[ERROR] an error occured, retrying... | [[{chunk.decode()}]]", flush=True)
return
while True:
try:
response = requests.post(
"https://api.gptplus.one/api/chat-process",
headers=headers,
json=json_data,
content_callback=format,
impersonate="chrome110",
)
exit(0)
except Exception as e:
print("[ERROR] an error occured, retrying... |", e, flush=True)
continue

View File

@ -1,81 +0,0 @@
import datetime
import json
import sys
import urllib.parse
from curl_cffi import requests
config = json.loads(sys.argv[1])
prompt = config["messages"][-1]["content"]
skill = "expert" if config["model"] == "gpt-4" else "intermediate"
json_data = json.dumps(
{
"question": prompt,
"options": {
"skill": skill,
"date": datetime.datetime.now().strftime("%d/%m/%Y"),
"language": "en",
"detailed": True,
"creative": True,
"customLinks": [],
},
},
separators=(",", ":"),
)
headers = {
"Content-Type": "application/json",
"Pragma": "no-cache",
"Accept": "*/*",
"Sec-Fetch-Site": "same-origin",
"Accept-Language": "en-GB,en;q=0.9",
"Cache-Control": "no-cache",
"Sec-Fetch-Mode": "cors",
"Content-Length": str(len(json_data)),
"Origin": "https://www.phind.com",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.4 Safari/605.1.15",
"Referer": f"https://www.phind.com/search?q={urllib.parse.quote(prompt)}&source=searchbox",
"Connection": "keep-alive",
"Host": "www.phind.com",
"Sec-Fetch-Dest": "empty",
}
def output(chunk):
try:
if b"PHIND_METADATA" in chunk:
return
if chunk == b"data: \r\ndata: \r\ndata: \r\n\r\n":
chunk = b"data: \n\r\n\r\n"
chunk = chunk.decode()
chunk = chunk.replace("data: \r\n\r\ndata: ", "data: \n")
chunk = chunk.replace("\r\ndata: \r\ndata: \r\n\r\n", "\n\r\n\r\n")
chunk = chunk.replace("data: ", "").replace("\r\n\r\n", "")
print(chunk, flush=True, end="")
except json.decoder.JSONDecodeError:
pass
while True:
try:
response = requests.post(
"https://www.phind.com/api/infer/answer",
headers=headers,
data=json_data,
content_callback=output,
timeout=999999,
impersonate="safari15_5",
)
exit(0)
except Exception as e:
print("an error occured, retrying... |", e, flush=True)
continue

View File

@ -1,53 +0,0 @@
import json
import sys
from re import findall
from curl_cffi import requests
config = json.loads(sys.argv[1])
prompt = config["messages"][-1]["content"]
headers = {
"authority": "chatbot.theb.ai",
"accept": "application/json, text/plain, */*",
"accept-language": "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",
"content-type": "application/json",
"origin": "https://chatbot.theb.ai",
"referer": "https://chatbot.theb.ai/",
"sec-ch-ua": '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"macOS"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36",
}
json_data = {"prompt": prompt, "options": {}}
def format(chunk):
try:
completion_chunk = findall(r'content":"(.*)"},"fin', chunk.decode())[0]
print(completion_chunk, flush=True, end="")
except Exception:
print(f"[ERROR] an error occured, retrying... | [[{chunk.decode()}]]", flush=True)
return
while True:
try:
response = requests.post(
"https://chatbot.theb.ai/api/chat-process",
headers=headers,
json=json_data,
content_callback=format,
impersonate="chrome110",
)
exit(0)
except Exception as e:
print("[ERROR] an error occured, retrying... |", e, flush=True)
continue

View File

@ -1,82 +0,0 @@
import json
import sys
import urllib.parse
from curl_cffi import requests
config = json.loads(sys.argv[1])
messages = config["messages"]
prompt = ""
def transform(messages: list) -> list:
result = []
i = 0
while i < len(messages):
if messages[i]["role"] == "user":
question = messages[i]["content"]
i += 1
if i < len(messages) and messages[i]["role"] == "assistant":
answer = messages[i]["content"]
i += 1
else:
answer = ""
result.append({"question": question, "answer": answer})
elif messages[i]["role"] == "assistant":
result.append({"question": "", "answer": messages[i]["content"]})
i += 1
elif messages[i]["role"] == "system":
result.append({"question": messages[i]["content"], "answer": ""})
i += 1
return result
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Accept-Language": "en-GB,en;q=0.9",
"Sec-Fetch-Mode": "navigate",
"Host": "you.com",
"Origin": "https://you.com",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.4 Safari/605.1.15",
"Referer": "https://you.com/api/streamingSearch?q=nice&safeSearch=Moderate&onShoppingPage=false&mkt=&responseFilter=WebPages,Translations,TimeZone,Computation,RelatedSearches&domain=youchat&queryTraceId=7a6671f8-5881-404d-8ea3-c3f8301f85ba&chat=%5B%7B%22question%22%3A%22hi%22%2C%22answer%22%3A%22Hello!%20How%20can%20I%20assist%20you%20today%3F%22%7D%5D&chatId=7a6671f8-5881-404d-8ea3-c3f8301f85ba&__cf_chl_tk=ex2bw6vn5vbLsUm8J5rDYUC0Bjzc1XZqka6vUl6765A-1684108495-0-gaNycGzNDtA",
"Connection": "keep-alive",
"Sec-Fetch-Dest": "document",
"Priority": "u=0, i",
}
if messages[-1]["role"] == "user":
prompt = messages[-1]["content"]
messages = messages[:-1]
params = urllib.parse.urlencode({"q": prompt, "domain": "youchat", "chat": transform(messages)})
def output(chunk):
if b'"youChatToken"' in chunk:
chunk_json = json.loads(chunk.decode().split("data: ")[1])
print(chunk_json["youChatToken"], flush=True, end="")
while True:
try:
response = requests.get(
f"https://you.com/api/streamingSearch?{params}",
headers=headers,
content_callback=output,
impersonate="safari15_5",
)
exit(0)
except Exception as e:
print("an error occured, retrying... |", e, flush=True)
continue

View File

@ -1,44 +0,0 @@
import os
from typing import get_type_hints
import requests
url = "https://hteyun.com"
model = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-16k-0613",
"gpt-3.5-turbo-0613",
]
supports_stream = True
needs_auth = False
def _create_completion(model: str, messages: list, stream: bool, temperature: float = 0.7, **kwargs):
headers = {
"Content-Type": "application/json",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,ja;q=0.6,zh-TW;q=0.5,zh;q=0.4",
"Origin": "https://hteyun.com",
"Referer": "https://hteyun.com/chat/",
}
data = {
"messages": messages,
"model": model,
"systemMessage": "You are ChatGPT, a large language model trained by OpenAI. Follow the user's instructions carefully. Respond using russian language.",
"temperature": 0.7,
"presence_penalty": 0,
}
response = requests.post(url + "/api/chat-stream", json=data, headers=headers, stream=True)
print(response.json())
# Извлечение текста из response
return response.json()["text"]
params = f"g4f.Providers.{os.path.basename(__file__)[:-3]} supports: " + "(%s)" % ", ".join(
[
f"{name}: {get_type_hints(_create_completion)[name].__name__}"
for name in _create_completion.__code__.co_varnames[: _create_completion.__code__.co_argcount]
]
)

View File

@ -1,35 +0,0 @@
from . import Provider
from .Providers import (
Aichat,
Ails,
AiService,
Bard,
Better,
Bing,
ChatFree,
ChatgptAi,
ChatgptLogin,
DeepAi,
Easychat,
Ezcht,
Fakeopen,
Forefront,
GetGpt,
Gravityengine,
H2o,
Liaobots,
Lockchat,
Mishalsgpt,
Phind,
Theb,
Vercel,
Weuseing,
Wewordle,
Xiaor,
You,
Yqcloud,
Zeabur,
hteyun,
)
Palm = Bard

View File

@ -1,5 +0,0 @@
## 🚀 API G4F
This API is built upon the [gpt4free](https://github.com/xtekky/gpt4free) project.

View File

@ -1,57 +0,0 @@
import sys
from g4f.models import Model, ModelUtils
from . import Provider
class ChatCompletion:
@staticmethod
def create(
model: Model.model or str,
messages: list,
provider: Provider.Provider = None,
stream: bool = False,
auth: str = False,
**kwargs,
):
kwargs["auth"] = auth
if provider and provider.needs_auth and not auth:
print(
f'ValueError: {provider.__name__} requires authentication (use auth="cookie or token or jwt ..." param)',
file=sys.stderr,
)
sys.exit(1)
try:
if isinstance(model, str):
try:
model = ModelUtils.convert[model]
except KeyError:
raise Exception(f"The model: {model} does not exist")
engine = model.best_provider if not provider else provider
if not engine.supports_stream and stream == True:
print(
f"ValueError: {engine.__name__} does not support 'stream' argument",
file=sys.stderr,
)
sys.exit(1)
print(f"Using {engine.__name__} provider")
return (
engine._create_completion(model.name, messages, stream, **kwargs)
if stream
else "".join(engine._create_completion(model.name, messages, stream, **kwargs))
)
except TypeError as e:
print(e)
arg: str = str(e).split("'")[1]
print(
f"ValueError: {engine.__name__} does not support '{arg}' argument",
file=sys.stderr,
)
sys.exit(1)

View File

@ -1,128 +0,0 @@
import uuid
import g4f
from g4f import ChatCompletion
TEST_PROMPT = "Generate a sentence with 'ocean'"
EXPECTED_RESPONSE_CONTAINS = "ocean"
class Provider:
def __init__(self, name, models):
"""
Initialize the provider with its name and models.
"""
self.name = name
self.models = models if isinstance(models, list) else [models]
def __str__(self):
return self.name
class ModelProviderManager:
def __init__(self):
"""
Initialize the manager that manages the working (active) providers for each model.
"""
self._working_model_providers = {}
def add_provider(self, model, provider_name):
"""
Add a provider to the working provider list of the specified model.
"""
if model not in self._working_model_providers:
self._working_model_providers[model] = []
self._working_model_providers[model].append(provider_name)
def get_working_providers(self):
"""
Return the currently active providers for each model.
"""
return self._working_model_providers
def _fetch_providers_having_models():
"""
Get providers that have models from g4f.Providers.
"""
model_providers = []
for provider_name in dir(g4f.Provider):
provider = getattr(g4f.Provider, provider_name)
if _is_provider_applicable(provider):
model_providers.append(Provider(provider_name, provider.model))
return model_providers
def _is_provider_applicable(provider):
"""
Check if the provider has a model and doesn't require authentication.
"""
return (
hasattr(provider, "model")
and hasattr(provider, "_create_completion")
and hasattr(provider, "needs_auth")
and not provider.needs_auth
)
def _generate_test_messages():
"""
Generate messages for testing.
"""
return [
{"role": "system", "content": "You are a trained AI assistant."},
{"role": "user", "content": TEST_PROMPT},
]
def _manage_chat_completion(manager, model_providers, test_messages):
"""
Generate chat completion for each provider's models and handle positive and negative results.
"""
for provider in model_providers:
for model in provider.models:
try:
response = _generate_chat_response(provider.name, model, test_messages)
if EXPECTED_RESPONSE_CONTAINS in response.lower():
_print_success_response(provider, model)
manager.add_provider(model, provider.name)
else:
raise Exception(f"Unexpected response: {response}")
except Exception as error:
_print_error_response(provider, model, error)
def _generate_chat_response(provider_name, model, test_messages):
"""
Generate a chat response given a provider name, a model, and test messages.
"""
return ChatCompletion.create(
model=model,
messages=test_messages,
chatId=str(uuid.uuid4()),
provider=getattr(g4f.Provider, provider_name),
)
def _print_success_response(provider, model):
print(f"\u2705 [{provider}] - [{model}]: Success")
def _print_error_response(provider, model, error):
print(f"\u26D4 [{provider}] - [{model}]: Error - {str(error)}")
def get_active_model_providers():
"""
Get providers that are currently working (active).
"""
model_providers = _fetch_providers_having_models()
test_messages = _generate_test_messages()
manager = ModelProviderManager()
_manage_chat_completion(manager, model_providers, test_messages)
return manager.get_working_providers()

View File

@ -1,223 +0,0 @@
from g4f import Provider
class Model:
class model:
name: str
base_provider: str
best_provider: str
class gpt_35_turbo:
name: str = "gpt-3.5-turbo"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Wewordle
class gpt_35_turbo_0613:
name: str = "gpt-3.5-turbo-0613"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Zeabur
class gpt_35_turbo_0301:
name: str = "gpt-3.5-turbo-0301"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Zeabur
class gpt_35_turbo_16k_0613:
name: str = "gpt-3.5-turbo-16k-0613"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Zeabur
class gpt_35_turbo_16k:
name: str = "gpt-3.5-turbo-16k"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.ChatFree
class gpt_4_dev:
name: str = "gpt-4-for-dev"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Phind
class gpt_4:
name: str = "gpt-4"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.ChatgptAi
class gpt_4_0613:
name: str = "gpt-4-0613"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Lockchat
best_providers: list = [Provider.Bing, Provider.Lockchat]
class claude_instant_v1_100k:
name: str = "claude-instant-v1-100k"
base_provider: str = "anthropic"
best_provider: Provider.Provider = Provider.Vercel
class claude_instant_v1:
name: str = "claude-instant-v1"
base_provider: str = "anthropic"
best_provider: Provider.Provider = Provider.Vercel
class claude_v1_100k:
name: str = "claude-v1-100k"
base_provider: str = "anthropic"
best_provider: Provider.Provider = Provider.Vercel
class claude_v1:
name: str = "claude-v1"
base_provider: str = "anthropic"
best_provider: Provider.Provider = Provider.Vercel
class alpaca_7b:
name: str = "alpaca-7b"
base_provider: str = "replicate"
best_provider: Provider.Provider = Provider.Vercel
class stablelm_tuned_alpha_7b:
name: str = "stablelm-tuned-alpha-7b"
base_provider: str = "replicate"
best_provider: Provider.Provider = Provider.Vercel
class bloom:
name: str = "bloom"
base_provider: str = "huggingface"
best_provider: Provider.Provider = Provider.Vercel
class bloomz:
name: str = "bloomz"
base_provider: str = "huggingface"
best_provider: Provider.Provider = Provider.Vercel
class flan_t5_xxl:
name: str = "flan-t5-xxl"
base_provider: str = "huggingface"
best_provider: Provider.Provider = Provider.Vercel
class flan_ul2:
name: str = "flan-ul2"
base_provider: str = "huggingface"
best_provider: Provider.Provider = Provider.Vercel
class gpt_neox_20b:
name: str = "gpt-neox-20b"
base_provider: str = "huggingface"
best_provider: Provider.Provider = Provider.Vercel
class oasst_sft_4_pythia_12b_epoch_35:
name: str = "oasst-sft-4-pythia-12b-epoch-3.5"
base_provider: str = "huggingface"
best_provider: Provider.Provider = Provider.Vercel
class santacoder:
name: str = "santacoder"
base_provider: str = "huggingface"
best_provider: Provider.Provider = Provider.Vercel
class command_medium_nightly:
name: str = "command-medium-nightly"
base_provider: str = "cohere"
best_provider: Provider.Provider = Provider.Vercel
class command_xlarge_nightly:
name: str = "command-xlarge-nightly"
base_provider: str = "cohere"
best_provider: Provider.Provider = Provider.Vercel
class code_cushman_001:
name: str = "code-cushman-001"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Vercel
class code_davinci_002:
name: str = "code-davinci-002"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Vercel
class text_ada_001:
name: str = "text-ada-001"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Vercel
class text_babbage_001:
name: str = "text-babbage-001"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Vercel
class text_curie_001:
name: str = "text-curie-001"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Vercel
class text_davinci_002:
name: str = "text-davinci-002"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Vercel
class text_davinci_003:
name: str = "text-davinci-003"
base_provider: str = "openai"
best_provider: Provider.Provider = Provider.Vercel
class palm:
name: str = "palm2"
base_provider: str = "google"
best_provider: Provider.Provider = Provider.Bard
class falcon_40b:
name: str = "falcon-40b"
base_provider: str = "huggingface"
best_provider: Provider.Provider = Provider.H2o
class falcon_7b:
name: str = "falcon-7b"
base_provider: str = "huggingface"
best_provider: Provider.Provider = Provider.H2o
class llama_13b:
name: str = "llama-13b"
base_provider: str = "huggingface"
best_provider: Provider.Provider = Provider.H2o
class ModelUtils:
convert: dict = {
"gpt-3.5-turbo": Model.gpt_35_turbo,
"gpt-3.5-turbo-0613": Model.gpt_35_turbo_0613,
"gpt-3.5-turbo-0301": Model.gpt_35_turbo_0301,
"gpt-4": Model.gpt_4,
"gpt-4-0613": Model.gpt_4_0613,
"gpt-4-for-dev": Model.gpt_4_dev,
"gpt-3.5-turbo-16k": Model.gpt_35_turbo_16k,
"gpt-3.5-turbo-16k-0613": Model.gpt_35_turbo_16k_0613,
"claude-instant-v1-100k": Model.claude_instant_v1_100k,
"claude-v1-100k": Model.claude_v1_100k,
"claude-instant-v1": Model.claude_instant_v1,
"claude-v1": Model.claude_v1,
"alpaca-7b": Model.alpaca_7b,
"stablelm-tuned-alpha-7b": Model.stablelm_tuned_alpha_7b,
"bloom": Model.bloom,
"bloomz": Model.bloomz,
"flan-t5-xxl": Model.flan_t5_xxl,
"flan-ul2": Model.flan_ul2,
"gpt-neox-20b": Model.gpt_neox_20b,
"oasst-sft-4-pythia-12b-epoch-3.5": Model.oasst_sft_4_pythia_12b_epoch_35,
"santacoder": Model.santacoder,
"command-medium-nightly": Model.command_medium_nightly,
"command-xlarge-nightly": Model.command_xlarge_nightly,
"code-cushman-001": Model.code_cushman_001,
"code-davinci-002": Model.code_davinci_002,
"text-ada-001": Model.text_ada_001,
"text-babbage-001": Model.text_babbage_001,
"text-curie-001": Model.text_curie_001,
"text-davinci-002": Model.text_davinci_002,
"text-davinci-003": Model.text_davinci_003,
"palm2": Model.palm,
"palm": Model.palm,
"google": Model.palm,
"google-bard": Model.palm,
"google-palm": Model.palm,
"bard": Model.palm,
"falcon-40b": Model.falcon_40b,
"falcon-7b": Model.falcon_7b,
"llama-13b": Model.llama_13b,
}

View File

@ -1,3 +0,0 @@
from typing import NewType
sha256 = NewType("sha_256_hash", str)

View File

@ -1,49 +0,0 @@
import browser_cookie3
class Utils:
browsers = [
browser_cookie3.chrome, # 62.74% market share
browser_cookie3.safari, # 24.12% market share
browser_cookie3.firefox, # 4.56% market share
browser_cookie3.edge, # 2.85% market share
browser_cookie3.opera, # 1.69% market share
browser_cookie3.brave, # 0.96% market share
browser_cookie3.opera_gx, # 0.64% market share
browser_cookie3.vivaldi, # 0.32% market share
]
def get_cookies(domain: str, setName: str = None, setBrowser: str = False) -> dict:
cookies = {}
if setBrowser != False:
for browser in Utils.browsers:
if browser.__name__ == setBrowser:
try:
for c in browser(domain_name=domain):
if c.name not in cookies:
cookies = cookies | {c.name: c.value}
except Exception:
pass
else:
for browser in Utils.browsers:
try:
for c in browser(domain_name=domain):
if c.name not in cookies:
cookies = cookies | {c.name: c.value}
except Exception:
pass
if setName:
try:
return {setName: cookies[setName]}
except ValueError:
print(f"Error: could not find {setName} cookie in any browser.")
exit(1)
else:
return cookies

View File

@ -1,7 +0,0 @@
from g4f.active_providers import get_active_model_providers
working_providers = get_active_model_providers()
print("\nWorking providers by model:")
for model, providers in working_providers.items():
print(f"{model}: {', '.join(providers)}")

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,48 @@
#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> weWordle(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> codeLinkAva(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);
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());
}

Some files were not shown because too many files have changed in this diff Show More