Package: g4f-fork
Forked fromhttps://github.com/xtekky/gpt4freeWritten by@xtekky& maintained by@hlohausBy using this repository or any code related to it, you agree to thelegal notice. The author is not responsible for any copies, forks, re-uploads made by other users, or anything else related to GPT4Free. This is the author's only account and repository. To prevent impersonation or irresponsible actions, please comply with the GNU GPL license this Repository uses.[!Note]Lastet version:pipinstall-Ug4fdockerpullhlohaus789/g4f🆕 What's NewJoin our Telegram Channel:t.me/g4f_channelJoin our Discord Group:discord.gg/XfybzPXPH5Explore the g4f Documentation (unfinished):g4f.mintlify.app| Contribute to the docs via:github.com/xtekky/gpt4free-docs📚 Table of ContentsForked from https://github.com/xtekky/gpt4free🆕 What's New📚 Table of Contents🛠️ Getting StartedDocker containerQuick start:Use python packagePrerequisites:Install using pypi:or:Docker for Developers💡 UsageTheg4fPackageChatCompletionCompletionProvidersUsing BrowserAsync SupportProxy and Timeout SupportInterference openai-proxy API (Use with openai python package)Run interference API from PyPi packageRun interference API from repo🚀 Providers and ModelsGPT-4GPT-3.5OtherModels🔗 Related GPT4Free Projects🤝 ContributeCreate Provider with AI ToolCreate Provider🙌 Contributors©️ Copyright⭐ Star History📄 License🛠️ Getting StartedDocker containerQuick start:Download and install DockerPull lastet image and run the container:dockerpullhlohaus789/g4f
dockerrun-p8080:80-p1337:1337-p7900:7900--shm-size="2g"hlohaus789/g4f:latestOpen the included client on:http://localhost:8080/chat/or set the api base in your client to:http://localhost:1337/v1(Optional) If you need to log in to a provider, you can view the desktop from the container here:http://localhost:7900/?autoconnect=1&resize=scale&password=secret.Use python packagePrerequisites:Download and install Python(Version 3.10+ is recommended).Install Google Chromefor providers with webdriverInstall using pypi:pip install -U g4for:Clone the GitHub repository:git clone https://github.com/xtekky/gpt4free.gitNavigate to the project directory:cd gpt4free(Recommended) Create a Python virtual environment:
You can follow thePython official documentationfor virtual environments.python3 -m venv venvActivate the virtual environment:On Windows:.\venv\Scripts\activateOn macOS and Linux:source venv/bin/activateInstall the required Python packages fromrequirements.txt:pip install -r requirements.txtCreate atest.pyfile in the root folder and start using the repo, further Instructions are belowimportg4f...Docker for DevelopersIf you have Docker installed, you can easily set up and run the project without manually installing dependencies.First, ensure you have both Docker and Docker Compose installed.Install DockerInstall Docker ComposeClone the GitHub repo:gitclonehttps://github.com/xtekky/gpt4free.gitNavigate to the project directory:cdgpt4freeBuild the Docker image:dockerpullselenium/node-chrome
docker-composebuildStart the service using Docker Compose:docker-composeupYour server will now be running athttp://localhost:1337. You can interact with the API or run your tests as you would normally.To stop the Docker containers, simply run:docker-composedown[!Note]
When using Docker, any changes you make to your local files will be reflected in the Docker container thanks to the volume mapping in thedocker-compose.ymlfile. If you add or remove dependencies, however, you'll need to rebuild the Docker image usingdocker-compose build.💡 UsageTheg4fPackageChatCompletionimportg4fg4f.debug.logging=True# Enable debug loggingg4f.debug.check_version=False# Disable automatic version checkingprint(g4f.Provider.Bing.params)# Print supported args for Bing# Using automatic a provider for the given model## Streamed completionresponse=g4f.ChatCompletion.create(model="gpt-3.5-turbo",messages=[{"role":"user","content":"Hello"}],stream=True,)formessageinresponse:print(message,flush=True,end='')## Normal responseresponse=g4f.ChatCompletion.create(model=g4f.models.gpt_4,messages=[{"role":"user","content":"Hello"}],)# Alternative model settingprint(response)Completionimportg4fallowed_models=['code-davinci-002','text-ada-001','text-babbage-001','text-curie-001','text-davinci-002','text-davinci-003']response=g4f.Completion.create(model='text-davinci-003',prompt='say this is a test')print(response)Providersimportg4f# Print all available providersprint([provider.__name__forprovidering4f.Provider.__providers__ifprovider.working])# Execute with a specific providerresponse=g4f.ChatCompletion.create(model="gpt-3.5-turbo",provider=g4f.Provider.Aichat,messages=[{"role":"user","content":"Hello"}],stream=True,)formessageinresponse:print(message)Using BrowserSome providers using a browser to bypass the bot protection. They using the selenium webdriver to control the browser. The browser settings and the login data are saved in a custom directory. If the headless mode is enabled, the browser windows are loaded invisibly. For performance reasons, it is recommended to reuse the browser instances and close them yourself at the end:importg4ffromundetected_chromedriverimportChrome,ChromeOptionsfromg4f.Providerimport(Bard,Poe,AItianhuSpace,MyShell,PerplexityAi,)options=ChromeOptions()options.add_argument("--incognito");webdriver=Chrome(options=options,headless=True)foridxinrange(10):response=g4f.ChatCompletion.create(model=g4f.models.default,provider=g4f.Provider.MyShell,messages=[{"role":"user","content":"Suggest me a name."}],webdriver=webdriver)print(f"{idx}:",response)webdriver.quit()Async SupportTo enhance speed and overall performance, execute providers asynchronously. The total execution time will be determined by the duration of the slowest provider's execution.importg4fimportasyncio_providers=[g4f.Provider.Aichat,g4f.Provider.ChatBase,g4f.Provider.Bing,g4f.Provider.GptGo,g4f.Provider.You,g4f.Provider.Yqcloud,]asyncdefrun_provider(provider:g4f.Provider.BaseProvider):try:response=awaitg4f.ChatCompletion.create_async(model=g4f.models.default,messages=[{"role":"user","content":"Hello"}],provider=provider,)print(f"{provider.__name__}:",response)exceptExceptionase:print(f"{provider.__name__}:",e)asyncdefrun_all():calls=[run_provider(provider)forproviderin_providers]awaitasyncio.gather(*calls)asyncio.run(run_all())Proxy and Timeout SupportAll providers support specifying a proxy and increasing timeout in the create functions.importg4fresponse=g4f.ChatCompletion.create(model=g4f.models.default,messages=[{"role":"user","content":"Hello"}],proxy="http://host:port",# or socks5://user:pass@host:porttimeout=120,# in secs)print(f"Result:",response)You can also set a proxy globally via an environment variable:exportG4F_PROXY="http://host:port"Interference openai-proxy API (Use with openai python package)Run interference API from PyPi packagefromg4f.apiimportrun_apirun_api()Run interference API from repoIf you want to use the embedding function, you need to get a Hugging Face token. You can get one atHugging Face Tokens. Make sure your role is set to write. If you have your token, just use it instead of the OpenAI api-key.Run server:g4fapiorpython-mg4f.api.runimportopenai# Set your Hugging Face token as the API key if you use embeddings# If you don't use embeddings, leave it emptyopenai.api_key="YOUR_HUGGING_FACE_TOKEN"# Replace with your actual token# Set the API base URL if needed, e.g., for a local development environmentopenai.api_base="http://localhost:1337/v1"defmain():chat_completion=openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=[{"role":"user","content":"write a poem about a tree"}],stream=True,)ifisinstance(chat_completion,dict):# Not streamingprint(chat_completion.choices[0].message.content)else:# Streamingfortokeninchat_completion:content=token["choices"][0]["delta"].get("content")ifcontentisnotNone:print(content,end="",flush=True)if__name__=="__main__":main()🚀 Providers and ModelsGPT-4WebsiteProviderGPT-3.5GPT-4StreamStatusAuthbing.comg4f.Provider.Bing❌✔️✔️❌chat.geekgpt.orgg4f.Provider.GeekGpt✔️✔️✔️❌gptchatly.comg4f.Provider.GptChatly✔️✔️❌❌liaobots.siteg4f.Provider.Liaobots✔️✔️✔️❌www.phind.comg4f.Provider.Phind❌✔️✔️❌raycast.comg4f.Provider.Raycast✔️✔️✔️✔️GPT-3.5WebsiteProviderGPT-3.5GPT-4StreamStatusAuthwww.aitianhu.comg4f.Provider.AItianhu✔️❌✔️❌chat3.aiyunos.topg4f.Provider.AItianhuSpace✔️❌✔️❌e.aiask.meg4f.Provider.AiAsk✔️❌✔️❌chat-gpt.orgg4f.Provider.Aichat✔️❌❌❌www.chatbase.cog4f.Provider.ChatBase✔️❌✔️❌chatforai.storeg4f.Provider.ChatForAi✔️❌✔️❌chatgpt.aig4f.Provider.ChatgptAi✔️❌✔️❌chatgptx.deg4f.Provider.ChatgptX✔️❌✔️❌chat-shared2.zhile.iog4f.Provider.FakeGpt✔️❌✔️❌freegpts1.aifree.siteg4f.Provider.FreeGpt✔️❌✔️❌gptalk.netg4f.Provider.GPTalk✔️❌✔️❌ai18.gptforlove.comg4f.Provider.GptForLove✔️❌✔️❌gptgo.aig4f.Provider.GptGo✔️❌✔️❌hashnode.comg4f.Provider.Hashnode✔️❌✔️❌app.myshell.aig4f.Provider.MyShell✔️❌✔️❌noowai.comg4f.Provider.NoowAi✔️❌✔️❌chat.openai.comg4f.Provider.OpenaiChat✔️❌✔️✔️theb.aig4f.Provider.Theb✔️❌✔️✔️sdk.vercel.aig4f.Provider.Vercel✔️❌✔️❌you.comg4f.Provider.You✔️❌✔️❌chat9.yqcloud.topg4f.Provider.Yqcloud✔️❌✔️❌chat.acytoo.comg4f.Provider.Acytoo✔️❌✔️❌aibn.ccg4f.Provider.Aibn✔️❌✔️❌ai.lsg4f.Provider.Ails✔️❌✔️❌chatgpt4online.orgg4f.Provider.Chatgpt4Online✔️❌✔️❌chat.chatgptdemo.netg4f.Provider.ChatgptDemo✔️❌✔️❌chatgptduo.comg4f.Provider.ChatgptDuo✔️❌❌❌chatgptfree.aig4f.Provider.ChatgptFree✔️❌❌❌chatgptlogin.aig4f.Provider.ChatgptLogin✔️❌✔️❌cromicle.topg4f.Provider.Cromicle✔️❌✔️❌gptgod.siteg4f.Provider.GptGod✔️❌✔️❌opchatgpts.netg4f.Provider.Opchatgpts✔️❌✔️❌chat.ylokh.xyzg4f.Provider.Ylokh✔️❌✔️❌OtherWebsiteProviderGPT-3.5GPT-4StreamStatusAuthbard.google.comg4f.Provider.Bard❌❌❌✔️deepinfra.comg4f.Provider.DeepInfra❌❌✔️❌huggingface.cog4f.Provider.HuggingChat❌❌✔️✔️www.llama2.aig4f.Provider.Llama2❌❌✔️❌open-assistant.iog4f.Provider.OpenAssistant❌❌✔️✔️ModelsModelBase ProviderProviderWebsitepalmGoogleg4f.Provider.Bardbard.google.comh2ogpt-gm-oasst1-en-2048-falcon-7b-v3Hugging Faceg4f.Provider.H2owww.h2o.aih2ogpt-gm-oasst1-en-2048-falcon-40b-v1Hugging Faceg4f.Provider.H2owww.h2o.aih2ogpt-gm-oasst1-en-2048-open-llama-13bHugging Faceg4f.Provider.H2owww.h2o.aiclaude-instant-v1Anthropicg4f.Provider.Vercelsdk.vercel.aiclaude-v1Anthropicg4f.Provider.Vercelsdk.vercel.aiclaude-v2Anthropicg4f.Provider.Vercelsdk.vercel.aicommand-light-nightlyCohereg4f.Provider.Vercelsdk.vercel.aicommand-nightlyCohereg4f.Provider.Vercelsdk.vercel.aigpt-neox-20bHugging Faceg4f.Provider.Vercelsdk.vercel.aioasst-sft-1-pythia-12bHugging Faceg4f.Provider.Vercelsdk.vercel.aioasst-sft-4-pythia-12b-epoch-3.5Hugging Faceg4f.Provider.Vercelsdk.vercel.aisantacoderHugging Faceg4f.Provider.Vercelsdk.vercel.aibloomHugging Faceg4f.Provider.Vercelsdk.vercel.aiflan-t5-xxlHugging Faceg4f.Provider.Vercelsdk.vercel.aicode-davinci-002OpenAIg4f.Provider.Vercelsdk.vercel.aigpt-3.5-turbo-16kOpenAIg4f.Provider.Vercelsdk.vercel.aigpt-3.5-turbo-16k-0613OpenAIg4f.Provider.Vercelsdk.vercel.aigpt-4-0613OpenAIg4f.Provider.Vercelsdk.vercel.aitext-ada-001OpenAIg4f.Provider.Vercelsdk.vercel.aitext-babbage-001OpenAIg4f.Provider.Vercelsdk.vercel.aitext-curie-001OpenAIg4f.Provider.Vercelsdk.vercel.aitext-davinci-002OpenAIg4f.Provider.Vercelsdk.vercel.aitext-davinci-003OpenAIg4f.Provider.Vercelsdk.vercel.aillama13b-v2-chatReplicateg4f.Provider.Vercelsdk.vercel.aillama7b-v2-chatReplicateg4f.Provider.Vercelsdk.vercel.ai🔗 Related GPT4Free Projects🎁 Projects⭐ Stars📚 Forks🛎 Issues📬 Pull requestsgpt4freegpt4free-tsFree AI API's & Potential Providers ListChatGPT-CloneChatGpt Discord BotNyx-Bot (Discord)LangChain gpt4freeChatGpt Telegram BotChatGpt Line BotAction Translate ReadmeLangchain Document GPT🤝 ContributeCreate Provider with AI ToolCall in your terminal thecreate_provider.pyscript:pythonetc/tool/create_provider.pyEnter your name for the new provider.Copy and paste thecURLcommand from your browser developer tools.Let the AI ​​create the provider for you.Customize the provider according to your needs.Create ProviderCheck out the currentlist of potential providers, or find your own provider source!Create a new file ing4f/Providerwith the name of the ProviderImplement a class that extendsBaseProvider.from__future__importannotationsfrom..typingimportAsyncResult,Messagesfrom.base_providerimportAsyncGeneratorProviderclassHogeService(AsyncGeneratorProvider):url="https://chat-gpt.com"working=Truesupports_gpt_35_turbo=True@classmethodasyncdefcreate_async_generator(cls,model:str,messages:Messages,proxy:str=None,**kwargs)->AsyncResult:yield""Here, you can adjust the settings, for example, if the website does support streaming, setsupports_streamtoTrue...Write code to request the provider increate_async_generatorandyieldthe response,even ifit's a one-time response, do not hesitate to look at other providers for inspirationAdd the Provider Name ing4f/Provider/__init__.pyfrom.HogeServiceimportHogeService__all__=[HogeService,]You are done !, test the provider by calling it:importg4fresponse=g4f.ChatCompletion.create(model='gpt-3.5-turbo',provider=g4f.Provider.PROVIDERNAME,messages=[{"role":"user","content":"test"}],stream=g4f.Provider.PROVIDERNAME.supports_stream)formessageinresponse:print(message,flush=True,end='')🙌 ContributorsA list of the contributors is availablehereTheVercel.pyfile contains code fromvercel-llm-apiby@ading2210, which is licensed under theGNU GPL v3Top 1 Contributor:@hlohaus©️ CopyrightThis program is licensed under theGNU GPL v3xtekky/gpt4free: Copyright (C) 2023 xtekky

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/>.⭐ Star History📄 LicenseThis project is licensed underGNU_GPL_v3.0.(🔼 Back to top)