Update readme / docs

This commit is contained in:
Heiner Lohaus 2024-02-19 19:34:28 +01:00
parent d55a4c3ef5
commit 5612ee4c8d
5 changed files with 293 additions and 257 deletions

269
README.md
View File

@ -91,7 +91,7 @@ docker run -p 8080:8080 -p 1337:1337 -p 7900:7900 --shm-size="2g" hlohaus789/g4f
or set the api base in your client to: [http://localhost:1337/v1](http://localhost:1337/v1) or set the api base in your client to: [http://localhost:1337/v1](http://localhost:1337/v1)
4. (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. 4. (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 package #### Use python
##### Prerequisites: ##### Prerequisites:
@ -104,32 +104,11 @@ Install all supported tools / all used packages:
``` ```
pip install -U g4f[all] pip install -U g4f[all]
``` ```
Install required packages for the OpenaiChat provider:
```
pip install -U g4f[openai]
```
Install required packages for the interference api:
```
pip install -U g4f[api]
```
Install required packages for the web interface:
```
pip install -U g4f[gui]
```
Install required packages for uploading / generating images:
```
pip install -U g4f[image]
```
Install required packages for providers with webdriver:
```
pip install -U g4f[webdriver]
```
Install required packages for proxy support:
```
pip install -U aiohttp_socks
```
##### or: Or use: [Partially Requirements](/docs/requirements.md)
##### Install from source:
1. Clone the GitHub repository: 1. Clone the GitHub repository:
@ -179,56 +158,14 @@ import g4f
... ...
``` ```
#### Docker for Developers ##### Install using Docker
If you have Docker installed, you can easily set up and run the project without manually installing dependencies. Or use: [Build Docker](/docs/docker.md)
1. First, ensure you have both Docker and Docker Compose installed.
- [Install Docker](https://docs.docker.com/get-docker/)
- [Install Docker Compose](https://docs.docker.com/compose/install/)
2. Clone the GitHub repo:
```bash
git clone https://github.com/xtekky/gpt4free.git
```
3. Navigate to the project directory:
```bash
cd gpt4free
```
4. Build the Docker image:
```bash
docker pull selenium/node-chrome
docker-compose build
```
5. Start the service using Docker Compose:
```bash
docker-compose up
```
Your server will now be running at `http://localhost:1337`. You can interact with the API or run your tests as you would normally.
To stop the Docker containers, simply run:
```bash
docker-compose down
```
> [!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 the `docker-compose.yml` file. If you add or remove dependencies, however, you'll need to rebuild the Docker image using `docker-compose build`.
## 💡 Usage ## 💡 Usage
### New Client with Image Generation #### Image Generation
#### not jet released
```python ```python
from g4f.client import Client from g4f.client import Client
@ -245,9 +182,15 @@ Result:
[![Image with cat](/docs/cat.jpeg)](/docs/client.md) [![Image with cat](/docs/cat.jpeg)](/docs/client.md)
[to the client API](/docs/client.md) #### Text Generation
### The Web UI and more:
- [Documentation for new Client](/docs/client.md)
- [Documentation for leagcy API](/docs/leagcy.md)
#### Web UI
To start the web interface, type the following codes in the command line. To start the web interface, type the following codes in the command line.
@ -256,81 +199,6 @@ from g4f.gui import run_gui
run_gui() run_gui()
``` ```
### The `g4f` Package
#### ChatCompletion
```python
import g4f
g4f.debug.logging = True # Enable debug logging
g4f.debug.version_check = False # Disable automatic version checking
print(g4f.Provider.Bing.params) # Print supported args for Bing
# Using automatic a provider for the given model
## Streamed completion
response = g4f.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello"}],
stream=True,
)
for message in response:
print(message, flush=True, end='')
## Normal response
response = g4f.ChatCompletion.create(
model=g4f.models.gpt_4,
messages=[{"role": "user", "content": "Hello"}],
) # Alternative model setting
print(response)
```
##### Completion
```python
import g4f
allowed_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)
```
##### Providers
```python
import g4f
# Print all available providers
print([
provider.__name__
for provider in g4f.Provider.__providers__
if provider.working
])
# Execute with a specific provider
response = g4f.ChatCompletion.create(
model="gpt-3.5-turbo",
provider=g4f.Provider.Aichat,
messages=[{"role": "user", "content": "Hello"}],
stream=True,
)
for message in response:
print(message)
```
##### Cookies / Access Token ##### Cookies / Access Token
For generating images with Bing and for the OpenAi Chat you need cookies or a token from your browser session. From Bing you need the "_U" cookie and from OpenAI you need the "access_token". You can pass the cookies / the access token in the create function or you use the `set_cookies` setter: For generating images with Bing and for the OpenAi Chat you need cookies or a token from your browser session. From Bing you need the "_U" cookie and from OpenAI you need the "access_token". You can pass the cookies / the access token in the create function or you use the `set_cookies` setter:
@ -358,111 +226,6 @@ pip install browser_cookie3
pip install g4f[webdriver] pip install g4f[webdriver]
``` ```
##### Image Upload & Generation
Image upload and generation are supported by three main providers:
- **Bing & Other GPT-4 Providers:** Utilizes Microsoft's Image Creator.
- **Google Gemini:** Available for free accounts with IP addresses outside Europe.
- **OpenaiChat with GPT-4:** Accessible for users with a Plus subscription.
```python
import g4f
# Setting up the request for image creation
response = g4f.ChatCompletion.create(
model=g4f.models.default, # Using the default model
provider=g4f.Provider.Gemini, # Specifying the provider as Gemini
messages=[{"role": "user", "content": "Create an image like this"}],
image=open("images/g4f.png", "rb"), # Image input can be a data URI, bytes, PIL Image, or IO object
image_name="g4f.png" # Optional: specifying the filename
)
# Displaying the response
print(response)
from g4f.image import ImageResponse
# Get image links from response
for chunk in g4f.ChatCompletion.create(
model=g4f.models.default, # Using the default model
provider=g4f.Provider.OpenaiChat, # Specifying the provider as OpenaiChat
messages=[{"role": "user", "content": "Create images with dogs"}],
access_token="...", # Need a access token from a plus user
stream=True,
ignore_stream=True
):
if isinstance(chunk, ImageResponse):
print(chunk.images) # Print generated image links
print(chunk.alt) # Print used prompt for image generation
```
##### Using Browser
Some 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:
```python
import g4f
from undetected_chromedriver import Chrome, ChromeOptions
from g4f.Provider import (
Bard,
Poe,
AItianhuSpace,
MyShell,
PerplexityAi,
)
options = ChromeOptions()
options.add_argument("--incognito");
webdriver = Chrome(options=options, headless=True)
for idx in range(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 Support
To enhance speed and overall performance, execute providers asynchronously. The total execution time will be determined by the duration of the slowest provider's execution.
```python
import g4f
import asyncio
_providers = [
g4f.Provider.Aichat,
g4f.Provider.ChatBase,
g4f.Provider.Bing,
g4f.Provider.GptGo,
g4f.Provider.You,
g4f.Provider.Yqcloud,
]
async def run_provider(provider: g4f.Provider.BaseProvider):
try:
response = await g4f.ChatCompletion.create_async(
model=g4f.models.default,
messages=[{"role": "user", "content": "Hello"}],
provider=provider,
)
print(f"{provider.__name__}:", response)
except Exception as e:
print(f"{provider.__name__}:", e)
async def run_all():
calls = [
run_provider(provider) for provider in _providers
]
await asyncio.gather(*calls)
asyncio.run(run_all())
```
##### Proxy and Timeout Support ##### Proxy and Timeout Support
All providers support specifying a proxy and increasing timeout in the create functions. All providers support specifying a proxy and increasing timeout in the create functions.

View File

@ -1,4 +1,4 @@
### G4F Client API Documentation (Beta Version) ### G4F - Client API (Beta Version)
#### Introduction #### Introduction
@ -31,7 +31,7 @@ from g4f.client import Client
from g4f.Provider import BingCreateImages, OpenaiChat, Gemini from g4f.Provider import BingCreateImages, OpenaiChat, Gemini
client = Client( client = Client(
text_provider=OpenaiChat, provider=OpenaiChat,
image_provider=Gemini, image_provider=Gemini,
proxies=None proxies=None
) )
@ -89,5 +89,4 @@ Original / Variant:
[![Original Image](/docs/cat.jpeg)](/docs/client.md) [![Original Image](/docs/cat.jpeg)](/docs/client.md)
[![Variant Image](/docs/cat.webp)](/docs/client.md) [![Variant Image](/docs/cat.webp)](/docs/client.md)
[Return to Documentation Home](/) [Return to Home](/)
```

46
docs/docker.md Normal file
View File

@ -0,0 +1,46 @@
### G4F - Docker
If you have Docker installed, you can easily set up and run the project without manually installing dependencies.
1. First, ensure you have both Docker and Docker Compose installed.
- [Install Docker](https://docs.docker.com/get-docker/)
- [Install Docker Compose](https://docs.docker.com/compose/install/)
2. Clone the GitHub repo:
```bash
git clone https://github.com/xtekky/gpt4free.git
```
3. Navigate to the project directory:
```bash
cd gpt4free
```
4. Build the Docker image:
```bash
docker pull selenium/node-chrome
docker-compose build
```
5. Start the service using Docker Compose:
```bash
docker-compose up
```
Your server will now be running at `http://localhost:1337`. You can interact with the API or run your tests as you would normally.
To stop the Docker containers, simply run:
```bash
docker-compose down
```
> [!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 the `docker-compose.yml` file. If you add or remove dependencies, however, you'll need to rebuild the Docker image using `docker-compose build`.
[Return to Home](/)

182
docs/leagcy.md Normal file
View File

@ -0,0 +1,182 @@
### G4F - Leagcy API
#### ChatCompletion
```python
import g4f
g4f.debug.logging = True # Enable debug logging
g4f.debug.version_check = False # Disable automatic version checking
print(g4f.Provider.Bing.params) # Print supported args for Bing
# Using automatic a provider for the given model
## Streamed completion
response = g4f.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello"}],
stream=True,
)
for message in response:
print(message, flush=True, end='')
## Normal response
response = g4f.ChatCompletion.create(
model=g4f.models.gpt_4,
messages=[{"role": "user", "content": "Hello"}],
) # Alternative model setting
print(response)
```
##### Completion
```python
import g4f
allowed_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)
```
##### Providers
```python
import g4f
# Print all available providers
print([
provider.__name__
for provider in g4f.Provider.__providers__
if provider.working
])
# Execute with a specific provider
response = g4f.ChatCompletion.create(
model="gpt-3.5-turbo",
provider=g4f.Provider.Aichat,
messages=[{"role": "user", "content": "Hello"}],
stream=True,
)
for message in response:
print(message)
```
##### Image Upload & Generation
Image upload and generation are supported by three main providers:
- **Bing & Other GPT-4 Providers:** Utilizes Microsoft's Image Creator.
- **Google Gemini:** Available for free accounts with IP addresses outside Europe.
- **OpenaiChat with GPT-4:** Accessible for users with a Plus subscription.
```python
import g4f
# Setting up the request for image creation
response = g4f.ChatCompletion.create(
model=g4f.models.default, # Using the default model
provider=g4f.Provider.Gemini, # Specifying the provider as Gemini
messages=[{"role": "user", "content": "Create an image like this"}],
image=open("images/g4f.png", "rb"), # Image input can be a data URI, bytes, PIL Image, or IO object
image_name="g4f.png" # Optional: specifying the filename
)
# Displaying the response
print(response)
from g4f.image import ImageResponse
# Get image links from response
for chunk in g4f.ChatCompletion.create(
model=g4f.models.default, # Using the default model
provider=g4f.Provider.OpenaiChat, # Specifying the provider as OpenaiChat
messages=[{"role": "user", "content": "Create images with dogs"}],
access_token="...", # Need a access token from a plus user
stream=True,
ignore_stream=True
):
if isinstance(chunk, ImageResponse):
print(chunk.images) # Print generated image links
print(chunk.alt) # Print used prompt for image generation
```
##### Using Browser
Some 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:
```python
import g4f
from undetected_chromedriver import Chrome, ChromeOptions
from g4f.Provider import (
Bard,
Poe,
AItianhuSpace,
MyShell,
PerplexityAi,
)
options = ChromeOptions()
options.add_argument("--incognito");
webdriver = Chrome(options=options, headless=True)
for idx in range(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 Support
To enhance speed and overall performance, execute providers asynchronously. The total execution time will be determined by the duration of the slowest provider's execution.
```python
import g4f
import asyncio
_providers = [
g4f.Provider.Aichat,
g4f.Provider.ChatBase,
g4f.Provider.Bing,
g4f.Provider.GptGo,
g4f.Provider.You,
g4f.Provider.Yqcloud,
]
async def run_provider(provider: g4f.Provider.BaseProvider):
try:
response = await g4f.ChatCompletion.create_async(
model=g4f.models.default,
messages=[{"role": "user", "content": "Hello"}],
provider=provider,
)
print(f"{provider.__name__}:", response)
except Exception as e:
print(f"{provider.__name__}:", e)
async def run_all():
calls = [
run_provider(provider) for provider in _providers
]
await asyncio.gather(*calls)
asyncio.run(run_all())
```
[Return to Home](/)

46
docs/requirements.md Normal file
View File

@ -0,0 +1,46 @@
### G4F - Additional Requirements
#### Introduction
You can install requirements partially or completely. So G4F can be used as you wish. You have the following options for this:
#### Options
Install required packages for the OpenaiChat provider:
```
pip install -U g4f[openai]
```
Install required packages for the interference api:
```
pip install -U g4f[api]
```
Install required packages for the web interface:
```
pip install -U g4f[gui]
```
Install required packages for uploading / generating images:
```
pip install -U g4f[image]
```
Install required packages for using the webdriver:
```
pip install -U g4f[webdriver]
```
Install required package for proxy support with aiohttp:
```
pip install -U aiohttp_socks
```
Install required package for loading cookies from browser:
```
pip install browser_cookie3
```
Install curl_cffi for better protection from being blocked:
```
pip install curl_cffi
```
Install all packages and uninstall this package for disabling the webdriver:
```
pip uninstall undetected-chromedriver
```
[Return to Home](/)