返回提交历史
Modified
README.md
+29
-43
Modified
docs/async_client.md
+247
-84
Modified
docs/client.md
+115
-67
Modified
docs/docker.md
+92
-23
Modified
docs/git.md
+95
-32
Added
docs/interference-api.md
+110
-0
Deleted
docs/interference.md
+0
-69
Added
docs/local.md
+164
-0
Modified
docs/providers-and-models.md
+39
-18
Modified
docs/requirements.md
+1
-0
XFEstudio/gpt4free
Updated almost all documentation and added new documentation for the local interface
d0b80e2b
代码差异
10 个文件
+892
-336
@@ -1,3 +1,5 @@
1
2
1
3

2
4
3
5
<a href="https://trendshift.io/repositories/1692" target="_blank"><img src="https://trendshift.io/api/badge/repositories/1692" alt="xtekky%2Fgpt4free | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
@@ -27,32 +29,28 @@ docker pull hlohaus789/g4f
27
29
```
28
30
29
31
## 🆕 What's New
30
31
- Added `gpt-4o`, simply use `gpt-4o` in `chat.completion.create`.
32
- Installation Guide for Windows (.exe): 💻 [#installation-guide-for-windows](#installation-guide-for-windows-exe)
33
- Join our Telegram Channel: 📨 [telegram.me/g4f_channel](https://telegram.me/g4f_channel)
34
- Join our Discord Group: 💬 [discord.gg/XfybzPXPH5](https://discord.gg/XfybzPXPH5)
35
- `g4f` now supports 100% local inference: 🧠 [local-docs](https://g4f.mintlify.app/docs/core/usage/local)
32
- **For comprehensive details on new features and updates, please refer to our [Releases](https://github.com/xtekky/gpt4free/releases) page**
33
- **Installation Guide for Windows (.exe):** 💻 [#installation-guide-for-windows](#installation-guide-for-windows-exe)
34
- **Join our Telegram Channel:** 📨 [telegram.me/g4f_channel](https://telegram.me/g4f_channel)
35
- **Join our Discord Group:** 💬 [discord.gg/XfybzPXPH5](https://discord.gg/XfybzPXPH5)
36
36
37
37
## 🔻 Site Takedown
38
38
39
39
Is your site on this repository and you want to take it down? Send an email to takedown@g4f.ai with proof it is yours and it will be removed as fast as possible. To prevent reproduction please secure your API. 😉
40
40
41
41
## 🚀 Feedback and Todo
42
43
You can always leave some feedback here: https://forms.gle/FeWV9RLEedfdkmFN6
44
45
As per the survey, here is a list of improvements to come
46
47
- [x] Update the repository to include the new openai library syntax (ex: `Openai()` class) | completed, use `g4f.client.Client`
48
- [ ] Golang implementation
49
- [ ] 🚧 Improve Documentation (in /docs & Guides, Howtos, & Do video tutorials)
50
- [x] Improve the provider status list & updates
51
- [ ] Tutorials on how to reverse sites to write your own wrapper (PoC only ofc)
52
- [x] Improve the Bing wrapper. (Wait and Retry or reuse conversation)
53
- [ ] 🚧 Write a standard provider performance test to improve the stability
54
- [ ] Potential support and development of local models
55
- [ ] 🚧 Improve compatibility and error handling
42
**You can always leave some feedback here:** https://forms.gle/FeWV9RLEedfdkmFN6
43
44
**As per the survey, here is a list of improvements to come**
45
- [x] Update the repository to include the new openai library syntax (ex: `Openai()` class) | completed, use `g4f.client.Client`
46
- [ ] Golang implementation
47
- [ ] 🚧 Improve Documentation (in /docs & Guides, Howtos, & Do video tutorials)
48
- [x] Improve the provider status list & updates
49
- [ ] Tutorials on how to reverse sites to write your own wrapper (PoC only ofc)
50
- [x] Improve the Bing wrapper. (Wait and Retry or reuse conversation)
51
- [ ] 🚧 Write a standard provider performance test to improve the stability
52
- [ ] Potential support and development of local models
53
- [ ] 🚧 Improve compatibility and error handling
56
54
57
55
## 📚 Table of Contents
58
56
@@ -70,7 +68,8 @@ As per the survey, here is a list of improvements to come
70
68
- [Text Generation](#text-generation)
71
69
- [Image Generation](#image-generation)
72
70
- [Web UI](#web-ui)
73
- [Interference API](#interference-api)
71
- [Interference API](docs/interference.md)
72
- [Local inference](docs/local.md)
74
73
- [Configuration](#configuration)
75
74
- [🚀 Providers and Models](docs/providers-and-models.md)
76
75
- [🔗 Powered by gpt4free](#-powered-by-gpt4free)
@@ -156,7 +155,6 @@ How do I load the project using git and installing the project requirements?
156
155
Read this tutorial and follow it step by step: [/docs/git](docs/git.md)
157
156
158
157
##### Install using Docker:
159
160
158
How do I build and run composer image from source?
161
159
Use docker-compose: [/docs/docker](docs/docker.md)
162
160
@@ -181,7 +179,6 @@ Hello! How can I assist you today?
181
179
```
182
180
183
181
#### Image Generation
184
185
182
```python
186
183
from g4f.client import Client
187
184
@@ -199,33 +196,26 @@ print(f"Generated image URL: {image_url}")
199
196
[](docs/client.md)
200
197
201
198
**Full Documentation for Python API**
202
203
- AsyncClient API from G4F: [/docs/async_client](docs/async_client.md)
204
- Client API like the OpenAI Python library: [/docs/client](docs/client.md)
205
- Legacy API with python modules: [/docs/legacy](docs/legacy.md)
199
- **Async Client API from G4F:** [/docs/async_client](docs/async_client.md)
200
- **Client API like the OpenAI Python library:** [/docs/client](docs/client.md)
201
- **Legacy API with python modules:** [/docs/legacy](docs/legacy.md)
206
202
207
203
#### Web UI
208
209
To start the web interface, type the following codes in python:
210
204
**To start the web interface, type the following codes in python:**
211
205
```python
212
206
from g4f.gui import run_gui
207
213
208
run_gui()
214
209
```
215
216
210
or execute the following command:
217
218
211
```bash
219
212
python -m g4f.cli gui -port 8080 -debug
220
213
```
221
214
222
215
#### Interference API
223
224
216
You can use the Interference API to serve other OpenAI integrations with G4F.
225
226
See docs: [/docs/interference](docs/interference.md)
227
228
Access with: http://localhost:1337/v1
217
**See docs:** [/docs/interference](docs/interference-api.md)
218
**Access with:** http://localhost:1337/v1
229
219
230
220
### Configuration
231
221
@@ -778,19 +768,15 @@ set G4F_PROXY=http://host:port
778
768
</table>
779
769
780
770
## 🤝 Contribute
781
782
771
We welcome contributions from the community. Whether you're adding new providers or features, or simply fixing typos and making small improvements, your input is valued. Creating a pull request is all it takes – our co-pilot will handle the code review process. Once all changes have been addressed, we'll merge the pull request into the main branch and release the updates at a later time.
783
772
784
773
###### Guide: How do i create a new Provider?
785
786
- Read: [/docs/guides/create_provider](docs/guides/create_provider.md)
774
- Read: [/docs/guides/create_provider](docs/guides/create_provider.md)
787
775
788
776
###### Guide: How can AI help me with writing code?
789
790
- Read: [/docs/guides/help_me](docs/guides/help_me.md)
777
- Read: [/docs/guides/help_me](docs/guides/help_me.md)
791
778
792
779
## 🙌 Contributors
793
794
780
A list of all contributors is available [here](https://github.com/xtekky/gpt4free/graphs/contributors)
795
781
796
782
<a href="https://github.com/xtekky" target="_blank"><img src="https://avatars.githubusercontent.com/u/98614666?v=4&s=45" width="45" title="xtekky"></a>
@@ -1,209 +1,372 @@
1
2
# How to Use the G4F AsyncClient API
3
4
The AsyncClient API is the asynchronous counterpart to the standard G4F Client API. It offers the same functionality as the synchronous API, but with the added benefit of improved performance due to its asynchronous nature.
5
6
Designed to maintain compatibility with the existing OpenAI API, the G4F AsyncClient API ensures a seamless transition for users already familiar with the OpenAI client.
1
# G4F - Async client API Guide
2
The G4F async client API is a powerful asynchronous interface for interacting with various AI models. This guide provides comprehensive information on how to use the API effectively, including setup, usage examples, best practices, and important considerations for optimal performance.
3
4
5
## Compatibility Note
6
The G4F async client API is designed to be compatible with the OpenAI API, making it easy for developers familiar with OpenAI's interface to transition to G4F.
7
8
## Table of Contents
9
- [Introduction](#introduction)
10
- [Key Features](#key-features)
11
- [Getting Started](#getting-started)
12
- [Initializing the Client](#initializing-the-client)
13
- [Configuration](#configuration)
14
- [Usage Examples](#usage-examples)
15
- [Text Completions](#text-completions)
16
- [Streaming Completions](#streaming-completions)
17
- [Using a Vision Model](#using-a-vision-model)
18
- [Image Generation](#image-generation)
19
- [Concurrent Tasks](#concurrent-tasks-with-asynciogather)
20
- [Available Models and Providers](#available-models-and-providers)
21
- [Error Handling and Best Practices](#error-handling-and-best-practices)
22
- [Rate Limiting and API Usage](#rate-limiting-and-api-usage)
23
- [Conclusion](#conclusion)
24
25
26
27
## Introduction
28
The G4F async client API is an asynchronous version of the standard G4F Client API. It offers the same functionality as the synchronous API but with improved performance due to its asynchronous nature. This guide will walk you through the key features and usage of the G4F async client API.
29
7
30
8
31
## Key Features
32
- **Custom Providers**: Use custom providers for enhanced flexibility.
33
- **ChatCompletion Interface**: Interact with chat models through the ChatCompletion class.
34
- **Streaming Responses**: Get responses iteratively as they are received.
35
- **Non-Streaming Responses**: Generate complete responses in a single call.
36
- **Image Generation and Vision Models**: Support for image-related tasks.
9
37
10
The G4F AsyncClient API offers several key features:
11
12
- **Custom Providers:** The G4F Client API allows you to use custom providers. This feature enhances the flexibility of the API, enabling it to cater to a wide range of use cases.
13
- **ChatCompletion Interface:** The G4F package provides an interface for interacting with chat models through the ChatCompletion class. This class provides methods for creating both streaming and non-streaming responses.
14
- **Streaming Responses:** The ChatCompletion.create method can return a response iteratively as and when they are received if the stream parameter is set to True.
15
- **Non-Streaming Responses:** The ChatCompletion.create method can also generate non-streaming responses.
16
- **Image Generation and Vision Models:** The G4F Client API also supports image generation and vision models, expanding its utility beyond text-based interactions.
17
18
## Initializing the Client
19
20
To utilize the G4F `AsyncClient`, you need to create a new instance. Below is an example showcasing how to initialize the client with custom providers:
38
21
39
40
## Getting Started
41
### Initializing the Client
42
**To use the G4F `Client`, create a new instance:**
22
43
```python
23
from g4f.client import AsyncClient
24
from g4f.Provider import BingCreateImages, OpenaiChat, Gemini
44
from g4f.client import Client
45
from g4f.Provider import OpenaiChat, Gemini
25
46
26
client = AsyncClient(
47
client = Client(
27
48
provider=OpenaiChat,
28
49
image_provider=Gemini,
29
# Add any other necessary parameters
50
# Add other parameters as needed
30
51
)
31
52
```
32
53
33
In this example:
34
- `provider` specifies the primary provider for generating text completions.
35
- `image_provider` specifies the provider for image-related functionalities.
36
37
## Configuration
38
39
You can configure the `AsyncClient` with additional settings, such as an API key for your provider and a proxy for all outgoing requests:
54
40
55
56
### Configuration
57
**Configure the `Client` with additional settings:**
41
58
```python
42
from g4f.client import AsyncClient
43
44
client = AsyncClient(
59
client = Client(
45
60
api_key="your_api_key_here",
46
61
proxies="http://user:pass@host",
47
# Add any other necessary parameters
62
# Add other parameters as needed
48
63
)
49
64
```
50
65
51
- `api_key`: Your API key for the provider.
52
- `proxies`: The proxy configuration for routing requests.
53
54
## Using AsyncClient
66
55
67
68
## Usage Examples
56
69
### Text Completions
57
58
You can use the `ChatCompletions` endpoint to generate text completions. Here’s how you can do it:
59
70
**Generate text completions using the ChatCompletions endpoint:**
60
71
```python
61
72
import asyncio
62
63
73
from g4f.client import Client
64
74
65
75
async def main():
66
76
client = Client()
77
67
78
response = await client.chat.completions.async_create(
68
79
model="gpt-3.5-turbo",
69
messages=[{"role": "user", "content": "say this is a test"}],
70
# Add any other necessary parameters
80
messages=[
81
{
82
"role": "user",
83
"content": "Say this is a test"
84
}
85
]
71
86
)
87
72
88
print(response.choices[0].message.content)
73
89
74
90
asyncio.run(main())
75
91
```
76
92
77
### Streaming Completions
78
79
The `AsyncClient` also supports streaming completions. This allows you to process the response incrementally as it is generated:
93
80
94
95
### Streaming Completions
96
**Process responses incrementally as they are generated:**
81
97
```python
82
98
import asyncio
83
84
99
from g4f.client import Client
85
100
86
101
async def main():
87
102
client = Client()
103
88
104
stream = await client.chat.completions.async_create(
89
105
model="gpt-4",
90
messages=[{"role": "user", "content": "say this is a test"}],
106
messages=[
107
{
108
"role": "user",
109
"content": "Say this is a test"
110
}
111
],
91
112
stream=True,
92
# Add any other necessary parameters
93
113
)
114
94
115
async for chunk in stream:
95
116
if chunk.choices[0].delta.content:
96
print(chunk.choices[0].delta.content or "", end="")
117
print(chunk.choices[0].delta.content, end="")
97
118
98
119
asyncio.run(main())
99
120
```
100
121
101
In this example:
102
- `stream=True` enables streaming of the response.
103
104
### Example: Using a Vision Model
105
106
The following code snippet demonstrates how to use a vision model to analyze an image and generate a description based on the content of the image. This example shows how to fetch an image, send it to the model, and then process the response.
122
107
123
124
### Using a Vision Model
125
**Analyze an image and generate a description:**
108
126
```python
109
127
import g4f
110
128
import requests
111
129
import asyncio
112
113
130
from g4f.client import Client
114
131
115
image = requests.get("https://raw.githubusercontent.com/xtekky/gpt4free/refs/heads/main/docs/cat.jpeg", stream=True).raw
116
# Or: image = open("docs/cat.jpeg", "rb")
117
118
119
132
async def main():
120
133
client = Client()
134
135
image = requests.get("https://raw.githubusercontent.com/xtekky/gpt4free/refs/heads/main/docs/cat.jpeg", stream=True).raw
136
121
137
response = await client.chat.completions.async_create(
122
138
model=g4f.models.default,
123
139
provider=g4f.Provider.Bing,
124
messages=[{"role": "user", "content": "What are on this image?"}],
140
messages=[
141
{
142
"role": "user",
143
"content": "What's in this image?"
144
}
145
],
125
146
image=image
126
# Add any other necessary parameters
127
147
)
148
128
149
print(response.choices[0].message.content)
129
150
130
151
asyncio.run(main())
131
152
```
132
153
133
### Image Generation:
134
135
You can generate images using a specified prompt:
154
136
155
156
### Image Generation
157
**Generate images using a specified prompt:**
137
158
```python
138
159
import asyncio
139
160
from g4f.client import Client
140
161
141
162
async def main():
142
163
client = Client()
164
143
165
response = await client.images.async_generate(
144
166
prompt="a white siamese cat",
145
model="dall-e-3",
146
# Add any other necessary parameters
167
model="dall-e-3"
147
168
)
169
148
170
image_url = response.data[0].url
149
171
print(f"Generated image URL: {image_url}")
150
172
151
173
asyncio.run(main())
152
174
```
153
175
154
#### Base64 as the response format
176
155
177
178
#### Base64 Response Format
156
179
```python
157
180
import asyncio
158
181
from g4f.client import Client
159
182
160
183
async def main():
161
184
client = Client()
185
162
186
response = await client.images.async_generate(
163
187
prompt="a white siamese cat",
164
188
model="dall-e-3",
165
189
response_format="b64_json"
166
# Add any other necessary parameters
167
190
)
191
168
192
base64_text = response.data[0].b64_json
169
193
print(base64_text)
170
194
171
195
asyncio.run(main())
172
196
```
173
197
174
### Example usage with asyncio.gather
175
176
Start two tasks at the same time:
198
177
199
200
### Concurrent Tasks with asyncio.gather
201
**Execute multiple tasks concurrently:**
178
202
```python
179
203
import asyncio
180
181
204
from g4f.client import Client
182
205
183
206
async def main():
184
207
client = Client()
185
208
186
209
task1 = client.chat.completions.async_create(
187
210
model="gpt-3.5-turbo",
188
messages=[{"role": "user", "content": "Say this is a test"}],
211
messages=[
212
{
213
"role": "user",
214
"content": "Say this is a test"
215
}
216
]
189
217
)
218
190
219
task2 = client.images.async_generate(
191
220
model="dall-e-3",
192
prompt="a white siamese cat",
221
prompt="a white siamese cat"
193
222
)
194
195
responses = await asyncio.gather(task1, task2)
196
223
197
chat_response, image_response = responses
198
224
chat_response, image_response = await asyncio.gather(task1, task2)
225
199
226
print("Chat Response:")
200
227
print(chat_response.choices[0].message.content)
201
202
print("\nImage Response:")
203
image_url = image_response.data[0].url
204
print(image_url)
228
229
print("Image Response:")
230
print(image_response.data[0].url)
205
231
206
232
asyncio.run(main())
207
233
```
208
234
235
236
237
## Available Models and Providers
238
The G4F AsyncClient supports a wide range of AI models and providers, allowing you to choose the best option for your specific use case. **Here's a brief overview of the available models and providers:**
239
240
### Models
241
- GPT-3.5-Turbo
242
- GPT-4
243
- DALL-E 3
244
- Gemini
245
- Claude (Anthropic)
246
- And more...
247
248
249
250
### Providers
251
- OpenAI
252
- Google (for Gemini)
253
- Anthropic
254
- Bing
255
- Custom providers
256
257
258
259
**To use a specific model or provider, specify it when creating the client or in the API call:**
260
```python
261
client = AsyncClient(provider=g4f.Provider.OpenaiChat)
262
263
# or
264
265
response = await client.chat.completions.async_create(
266
model="gpt-4",
267
provider=g4f.Provider.Bing,
268
messages=[
269
{
270
"role": "user",
271
"content": "Hello, world!"
272
}
273
]
274
)
275
```
276
277
278
279
## Error Handling and Best Practices
280
Implementing proper error handling and following best practices is crucial when working with the G4F AsyncClient API. This ensures your application remains robust and can gracefully handle various scenarios. **Here are some key practices to follow:**
281
282
1. **Use try-except blocks to catch and handle exceptions:**
283
```python
284
try:
285
response = await client.chat.completions.async_create(
286
model="gpt-3.5-turbo",
287
messages=[
288
{
289
"role": "user",
290
"content": "Hello, world!"
291
}
292
]
293
)
294
except Exception as e:
295
print(f"An error occurred: {e}")
296
```
297
298
2. **Check the response status and handle different scenarios:**
299
```python
300
if response.choices:
301
print(response.choices[0].message.content)
302
else:
303
print("No response generated")
304
```
305
306
3. **Implement retries for transient errors:**
307
```python
308
import asyncio
309
from tenacity import retry, stop_after_attempt, wait_exponential
310
311
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
312
async def make_api_call():
313
# Your API call here
314
pass
315
```
316
317
318
319
## Rate Limiting and API Usage
320
When working with the G4F AsyncClient API, it's important to implement rate limiting and monitor your API usage. This helps ensure fair usage, prevents overloading the service, and optimizes your application's performance. Here are some key strategies to consider:
321
322
323
1. **Implement rate limiting in your application:**
324
```python
325
import asyncio
326
from aiolimiter import AsyncLimiter
327
328
rate_limit = AsyncLimiter(max_rate=10, time_period=1) # 10 requests per second
329
330
async def make_api_call():
331
async with rate_limit:
332
# Your API call here
333
pass
334
```
335
336
337
338
2. **Monitor your API usage and implement logging:**
339
```python
340
import logging
341
342
logging.basicConfig(level=logging.INFO)
343
logger = logging.getLogger(__name__)
344
345
async def make_api_call():
346
try:
347
response = await client.chat.completions.async_create(...)
348
logger.info(f"API call successful. Tokens used: {response.usage.total_tokens}")
349
except Exception as e:
350
logger.error(f"API call failed: {e}")
351
```
352
353
354
355
3. **Use caching to reduce API calls for repeated queries:**
356
```python
357
from functools import lru_cache
358
359
@lru_cache(maxsize=100)
360
def get_cached_response(query):
361
# Your API call here
362
pass
363
```
364
365
## Conclusion
366
The G4F async client API provides a powerful and flexible way to interact with various AI models asynchronously. By leveraging its features and following best practices, you can build efficient and responsive applications that harness the power of AI for text generation, image analysis, and image creation.
367
368
Remember to handle errors gracefully, implement rate limiting, and monitor your API usage to ensure optimal performance and reliability in your applications.
369
370
---
371
209
372
[Return to Home](/)
@@ -1,32 +1,51 @@
1
1
2
### G4F - Client API
3
4
#### Introduction
5
2
# G4F Client API Guide
3
4
5
## Table of Contents
6
- [Introduction](#introduction)
7
- [Getting Started](#getting-started)
8
- [Switching to G4F Client](#switching-to-g4f-client)
9
- [Initializing the Client](#initializing-the-client)
10
- [Configuration](#configuration)
11
- [Usage Examples](#usage-examples)
12
- [Text Completions](#text-completions)
13
- [Streaming Completions](#streaming-completions)
14
- [Image Generation](#image-generation)
15
- [Creating Image Variations](#creating-image-variations)
16
- [Advanced Usage](#advanced-usage)
17
- [Using a List of Providers with RetryProvider](#using-a-list-of-providers-with-retryprovider)
18
- [Using GeminiProVision](#using-geminiprovision)
19
- [Using a Vision Model](#using-a-vision-model)
20
- [Command-line Chat Program](#command-line-chat-program)
21
22
23
24
## Introduction
6
25
Welcome to the G4F Client API, a cutting-edge tool for seamlessly integrating advanced AI capabilities into your Python applications. This guide is designed to facilitate your transition from using the OpenAI client to the G4F Client, offering enhanced features while maintaining compatibility with the existing OpenAI API.
7
26
8
#### Getting Started
9
10
**Switching to G4F Client:**
27
## Getting Started
28
### Switching to G4F Client
29
**To begin using the G4F Client, simply update your import statement in your Python code:**
11
30
12
To begin using the G4F Client, simply update your import statement in your Python code:
13
14
Old Import:
31
**Old Import:**
15
32
```python
16
33
from openai import OpenAI
17
34
```
18
35
19
New Import:
36
37
38
**New Import:**
20
39
```python
21
40
from g4f.client import Client as OpenAI
22
41
```
23
42
24
The G4F Client preserves the same familiar API interface as OpenAI, ensuring a smooth transition process.
43
25
44
26
### Initializing the Client
27
28
To utilize the G4F Client, create an new instance. Below is an example showcasing custom providers:
45
The G4F Client preserves the same familiar API interface as OpenAI, ensuring a smooth transition process.
29
46
47
## Initializing the Client
48
To utilize the G4F Client, create a new instance. **Below is an example showcasing custom providers:**
30
49
```python
31
50
from g4f.client import Client
32
51
from g4f.Provider import BingCreateImages, OpenaiChat, Gemini
@@ -37,49 +56,61 @@ client = Client(
37
56
# Add any other necessary parameters
38
57
)
39
58
```
59
40
60
41
61
## Configuration
42
43
You can set an "api_key" for your provider in the client.
44
And you also have the option to define a proxy for all outgoing requests:
45
62
**You can set an `api_key` for your provider in the client and define a proxy for all outgoing requests:**
46
63
```python
47
64
from g4f.client import Client
48
65
49
66
client = Client(
50
api_key="...",
67
api_key="your_api_key_here",
51
68
proxies="http://user:pass@host",
52
69
# Add any other necessary parameters
53
70
)
54
71
```
55
72
56
#### Usage Examples
57
58
**Text Completions:**
59
60
You can use the `ChatCompletions` endpoint to generate text completions as follows:
73
61
74
75
## Usage Examples
76
### Text Completions
77
**Generate text completions using the `ChatCompletions` endpoint:**
62
78
```python
63
79
from g4f.client import Client
64
80
65
81
client = Client()
82
66
83
response = client.chat.completions.create(
67
84
model="gpt-3.5-turbo",
68
messages=[{"role": "user", "content": "Say this is a test"}],
85
messages=[
86
{
87
"role": "user",
88
"content": "Say this is a test"
89
}
90
]
69
91
# Add any other necessary parameters
70
92
)
93
71
94
print(response.choices[0].message.content)
72
95
```
73
96
74
Also streaming are supported:
97
75
98
99
### Streaming Completions
100
**Process responses incrementally as they are generated:**
76
101
```python
77
102
from g4f.client import Client
78
103
79
104
client = Client()
105
80
106
stream = client.chat.completions.create(
81
107
model="gpt-4",
82
messages=[{"role": "user", "content": "Say this is a test"}],
108
messages=[
109
{
110
"role": "user",
111
"content": "Say this is a test"
112
}
113
],
83
114
stream=True,
84
115
)
85
116
@@ -88,101 +119,104 @@ for chunk in stream:
88
119
print(chunk.choices[0].delta.content or "", end="")
89
120
```
90
121
91
**Image Generation:**
92
93
Generate images using a specified prompt:
122
94
123
124
### Image Generation
125
**Generate images using a specified prompt:**
95
126
```python
96
127
from g4f.client import Client
97
128
98
129
client = Client()
130
99
131
response = client.images.generate(
100
132
model="dall-e-3",
101
prompt="a white siamese cat",
133
prompt="a white siamese cat"
102
134
# Add any other necessary parameters
103
135
)
104
136
105
137
image_url = response.data[0].url
138
106
139
print(f"Generated image URL: {image_url}")
107
140
```
108
141
109
**Creating Image Variations:**
110
111
Create variations of an existing image:
142
112
143
144
### Creating Image Variations
145
**Create variations of an existing image:**
113
146
```python
114
147
from g4f.client import Client
115
148
116
149
client = Client()
150
117
151
response = client.images.create_variation(
118
152
image=open("cat.jpg", "rb"),
119
model="bing",
153
model="bing"
120
154
# Add any other necessary parameters
121
155
)
122
156
123
157
image_url = response.data[0].url
158
124
159
print(f"Generated image URL: {image_url}")
125
160
```
126
Original / Variant:
127
161
128
[](/docs/client.md) [](/docs/client.md)
162
129
163
130
#### Use a list of providers with RetryProvider
164
## Advanced Usage
131
165
166
### Using a List of Providers with RetryProvider
132
167
```python
133
168
from g4f.client import Client
134
169
from g4f.Provider import RetryProvider, Phind, FreeChatgpt, Liaobots
135
136
170
import g4f.debug
171
137
172
g4f.debug.logging = True
138
173
g4f.debug.version_check = False
139
174
140
175
client = Client(
141
176
provider=RetryProvider([Phind, FreeChatgpt, Liaobots], shuffle=False)
142
177
)
178
143
179
response = client.chat.completions.create(
144
180
model="",
145
messages=[{"role": "user", "content": "Hello"}],
181
messages=[
182
{
183
"role": "user",
184
"content": "Hello"
185
}
186
]
146
187
)
147
print(response.choices[0].message.content)
148
```
149
188
150
```
151
Using RetryProvider provider
152
Using Phind provider
153
How can I assist you today?
189
print(response.choices[0].message.content)
154
190
```
155
191
156
#### Advanced example using GeminiProVision
157
192
193
### Using GeminiProVision
158
194
```python
159
195
from g4f.client import Client
160
196
from g4f.Provider.GeminiPro import GeminiPro
161
197
162
198
client = Client(
163
api_key="...",
199
api_key="your_api_key_here",
164
200
provider=GeminiPro
165
201
)
202
166
203
response = client.chat.completions.create(
167
204
model="gemini-pro-vision",
168
messages=[{"role": "user", "content": "What are on this image?"}],
205
messages=[
206
{
207
"role": "user",
208
"content": "What are on this image?"
209
}
210
],
169
211
image=open("docs/waterfall.jpeg", "rb")
170
212
)
171
print(response.choices[0].message.content)
172
```
173
213
214
print(response.choices[0].message.content)
174
215
```
175
User: What are on this image?
176
```
177
178

179
```
180
Bot: There is a waterfall in the middle of a jungle. There is a rainbow over...
181
```
182
183
### Example: Using a Vision Model
184
The following code snippet demonstrates how to use a vision model to analyze an image and generate a description based on the content of the image. This example shows how to fetch an image, send it to the model, and then process the response.
185
216
217
218
### Using a Vision Model
219
**Analyze an image and generate a description:**
186
220
```python
187
221
import g4f
188
222
import requests
@@ -192,17 +226,26 @@ image = requests.get("https://raw.githubusercontent.com/xtekky/gpt4free/refs/hea
192
226
# Or: image = open("docs/cat.jpeg", "rb")
193
227
194
228
client = Client()
229
195
230
response = client.chat.completions.create(
196
231
model=g4f.models.default,
197
messages=[{"role": "user", "content": "What are on this image?"}],
232
messages=[
233
{
234
"role": "user",
235
"content": "What are on this image?"
236
}
237
],
198
238
provider=g4f.Provider.Bing,
199
image=image,
239
image=image
200
240
# Add any other necessary parameters
201
241
)
242
202
243
print(response.choices[0].message.content)
203
244
```
204
245
205
#### Advanced example: A command-line program
246
247
## Command-line Chat Program
248
**Here's an example of a simple command-line chat program using the G4F Client:**
206
249
```python
207
250
import g4f
208
251
from g4f.client import Client
@@ -216,7 +259,7 @@ messages = []
216
259
while True:
217
260
# Get user input
218
261
user_input = input("You: ")
219
262
220
263
# Check if the user wants to exit the chat
221
264
if user_input.lower() == "exit":
222
265
print("Exiting chat...")
@@ -238,8 +281,13 @@ while True:
238
281
239
282
# Update the conversation history with GPT's response
240
283
messages.append({"role": "assistant", "content": gpt_response})
284
241
285
except Exception as e:
242
286
print(f"An error occurred: {e}")
243
287
```
288
289
This guide provides a comprehensive overview of the G4F Client API, demonstrating its versatility in handling various AI tasks, from text generation to image analysis and creation. By leveraging these features, you can build powerful and responsive applications that harness the capabilities of advanced AI models.
290
244
291
292
---
245
293
[Return to Home](/)
@@ -1,45 +1,114 @@
1
### G4F - Docker Setup
2
1
3
Easily set up and run the G4F project using Docker without the hassle of manual dependency installation.
2
# G4F Docker Setup
4
3
5
1. **Prerequisites:**
6
- [Install Docker](https://docs.docker.com/get-docker/)
7
- [Install Docker Compose](https://docs.docker.com/compose/install/)
4
## Table of Contents
5
- [Prerequisites](#prerequisites)
6
- [Installation and Setup](#installation-and-setup)
7
- [Testing the API](#testing-the-api)
8
- [Troubleshooting](#troubleshooting)
9
- [Stopping the Service](#stopping-the-service)
8
10
9
2. **Clone the Repository:**
10
11
11
```bash
12
git clone https://github.com/xtekky/gpt4free.git
13
```
12
## Prerequisites
13
**Before you begin, ensure you have the following installed on your system:**
14
- [Docker](https://docs.docker.com/get-docker/)
15
- [Docker Compose](https://docs.docker.com/compose/install/)
16
- Python 3.7 or higher
17
- pip (Python package manager)
14
18
15
3. **Navigate to the Project Directory:**
19
**Note:** If you encounter issues with Docker, you can run the project directly using Python.
16
20
17
```bash
18
cd gpt4free
19
```
21
## Installation and Setup
22
23
### Docker Method (Recommended)
24
1. **Clone the Repository**
25
```bash
26
git clone https://github.com/xtekky/gpt4free.git
27
cd gpt4free
28
```
29
30
2. **Build and Run with Docker Compose**
31
```bash
32
docker-compose up --build
33
```
34
35
3. **Access the API**
36
The server will be accessible at `http://localhost:1337`
37
38
### Non-Docker Method
39
If you encounter issues with Docker, you can run the project directly using Python:
40
41
1. **Clone the Repository**
42
```bash
43
git clone https://github.com/xtekky/gpt4free.git
44
cd gpt4free
45
```
46
47
2. **Install Dependencies**
48
```bash
49
pip install -r requirements.txt
50
```
20
51
21
4. **Build the Docker Image:**
52
3. **Run the Server**
53
```bash
54
python -m g4f.api.run
55
```
22
56
57
4. **Access the API**
58
The server will be accessible at `http://localhost:1337`
59
60
## Testing the API
61
**You can test the API using curl or by creating a simple Python script:**
62
### Using curl
23
63
```bash
24
docker pull selenium/node-chrome
25
docker-compose build
64
curl -X POST -H "Content-Type: application/json" -d '{"prompt": "What is the capital of France?"}' http://localhost:1337/chat/completions
26
65
```
27
66
28
5. **Start the Service:**
67
### Using Python
68
**Create a file named `test_g4f.py` with the following content:**
69
```python
70
import requests
71
72
url = "http://localhost:1337/v1/chat/completions"
73
body = {
74
"model": "gpt-3.5-turbo",
75
"stream": False,
76
"messages": [
77
{"role": "assistant", "content": "What can you do?"}
78
]
79
}
80
81
json_response = requests.post(url, json=body).json().get('choices', [])
82
83
for choice in json_response:
84
print(choice.get('message', {}).get('content', ''))
85
```
29
86
87
**Run the script:**
30
88
```bash
31
docker-compose up
89
python test_g4f.py
32
90
```
33
91
34
Your server will now be accessible at `http://localhost:1337`. Interact with the API or run tests as usual.
92
## Troubleshooting
93
- If you encounter issues with Docker, try running the project directly using Python as described in the Non-Docker Method.
94
- Ensure that you have the necessary permissions to run Docker commands. You might need to use `sudo` or add your user to the `docker` group.
95
- If the server doesn't start, check the logs for any error messages and ensure all dependencies are correctly installed.
35
96
36
To stop the Docker containers, simply run:
97
**_For more detailed information on API endpoints and usage, refer to the [G4F API documentation](docs/interference-api.md)._**
37
98
99
100
101
## Stopping the Service
102
103
### Docker Method
104
**To stop the Docker containers, use the following command:**
38
105
```bash
39
106
docker-compose down
40
107
```
41
108
42
> [!Note]
43
> Changes made to local files reflect in the Docker container due to volume mapping in `docker-compose.yml`. However, if you add or remove dependencies, rebuild the Docker image using `docker-compose build`.
109
### Non-Docker Method
110
If you're running the server directly with Python, you can stop it by pressing Ctrl+C in the terminal where it's running.
111
112
---
44
113
45
[Return to Home](/)
114
[Return to Home](/)
@@ -1,66 +1,129 @@
1
### G4F - Installation Guide
2
1
3
Follow these steps to install G4F from the source code:
2
# G4F - Git Installation Guide
4
3
5
1. **Clone the Repository:**
4
This guide provides step-by-step instructions for installing G4F from the source code using Git.
6
5
7
```bash
8
git clone https://github.com/xtekky/gpt4free.git
9
```
10
6
11
2. **Navigate to the Project Directory:**
7
## Table of Contents
12
8
13
```bash
14
cd gpt4free
15
```
9
1. [Prerequisites](#prerequisites)
10
2. [Installation Steps](#installation-steps)
11
1. [Clone the Repository](#1-clone-the-repository)
12
2. [Navigate to the Project Directory](#2-navigate-to-the-project-directory)
13
3. [Set Up a Python Virtual Environment](#3-set-up-a-python-virtual-environment-recommended)
14
4. [Activate the Virtual Environment](#4-activate-the-virtual-environment)
15
5. [Install Dependencies](#5-install-dependencies)
16
6. [Verify Installation](#6-verify-installation)
17
3. [Usage](#usage)
18
4. [Troubleshooting](#troubleshooting)
19
5. [Additional Resources](#additional-resources)
16
20
17
3. **(Optional) Create a Python Virtual Environment:**
21
---
18
22
19
It's recommended to isolate your project dependencies. You can follow the [Python official documentation](https://docs.python.org/3/tutorial/venv.html) for virtual environments.
23
## Prerequisites
20
24
21
```bash
22
python3 -m venv venv
23
```
25
Before you begin, ensure you have the following installed on your system:
26
- Git
27
- Python 3.7 or higher
28
- pip (Python package installer)
24
29
25
4. **Activate the Virtual Environment:**
26
27
- On Windows:
30
## Installation Steps
28
31
32
### 1. Clone the Repository
33
**Open your terminal and run the following command to clone the G4F repository:**
29
34
```bash
30
.\venv\Scripts\activate
35
git clone https://github.com/xtekky/gpt4free.git
31
36
```
32
37
33
- On macOS and Linux:
38
### 2. Navigate to the Project Directory
39
**Change to the project directory:**
40
```bash
41
cd gpt4free
42
```
34
43
44
### 3. Set Up a Python Virtual Environment (Recommended)
45
**It's best practice to use a virtual environment to manage project dependencies:**
35
46
```bash
36
source venv/bin/activate
47
python3 -m venv venv
37
48
```
38
49
39
5. **Install Minimum Requirements:**
50
### 4. Activate the Virtual Environment
51
**Activate the virtual environment based on your operating system:**
52
- **Windows:**
53
```bash
54
.\venv\Scripts\activate
55
```
40
56
41
Install the minimum required packages:
57
- **macOS and Linux:**
58
```bash
59
source venv/bin/activate
60
```
42
61
62
### 5. Install Dependencies
63
**You have two options for installing dependencies:**
64
65
#### Option A: Install Minimum Requirements
66
**For a lightweight installation, use:**
43
67
```bash
44
68
pip install -r requirements-min.txt
45
69
```
46
70
47
6. **Or Install All Packages from `requirements.txt`:**
48
49
If you prefer, you can install all packages listed in `requirements.txt`:
50
71
#### Option B: Install All Packages
72
**For a full installation with all features, use:**
51
73
```bash
52
74
pip install -r requirements.txt
53
75
```
54
76
55
7. **Start Using the Repository:**
56
77
### 6. Verify Installation
57
78
You can now create Python scripts and utilize the G4F functionalities. Here's a basic example:
58
79
59
Create a `test.py` file in the root folder and start using the repository:
60
80
**Create a `g4f-test.py` file in the root folder and start using the repository:**
61
81
```python
62
82
import g4f
63
83
# Your code here
64
84
```
65
85
66
[Return to Home](/)
86
## Usage
87
**After installation, you can start using G4F in your Python scripts. Here's a basic example:**
88
```python
89
import g4f
90
91
# Your G4F code here
92
# For example:
93
from g4f.client import Client
94
95
client = Client()
96
97
response = client.chat.completions.create(
98
model="gpt-3.5-turbo",
99
messages=[
100
{
101
"role": "user",
102
"content": "Say this is a test"
103
}
104
]
105
# Add any other necessary parameters
106
)
107
108
print(response.choices[0].message.content)
109
```
110
111
## Troubleshooting
112
**If you encounter any issues during installation or usage:**
113
1. Ensure all prerequisites are correctly installed.
114
2. Check that you're in the correct directory and the virtual environment is activated.
115
3. Try reinstalling the dependencies.
116
4. Consult the [G4F documentation](https://github.com/xtekky/gpt4free) for more detailed information.
117
118
## Additional Resources
119
- [G4F GitHub Repository](https://github.com/xtekky/gpt4free)
120
- [Python Virtual Environments Guide](https://docs.python.org/3/tutorial/venv.html)
121
- [pip Documentation](https://pip.pypa.io/en/stable/)
122
123
---
124
125
**_For more information or support, please visit the [G4F GitHub Issues page](https://github.com/xtekky/gpt4free/issues)._**
126
127
128
---
129
[Return to Home](/)
@@ -0,0 +1,110 @@
1
2
# G4F - Interference API Usage Guide
3
4
5
## Table of Contents
6
- [Introduction](#introduction)
7
- [Running the Interference API](#running-the-interference-api)
8
- [From PyPI Package](#from-pypi-package)
9
- [From Repository](#from-repository)
10
- [Usage with OpenAI Library](#usage-with-openai-library)
11
- [Usage with Requests Library](#usage-with-requests-library)
12
- [Key Points](#key-points)
13
14
## Introduction
15
The Interference API allows you to serve other OpenAI integrations with G4F. It acts as a proxy, translating requests to the OpenAI API into requests to the G4F providers.
16
17
## Running the Interference API
18
19
### From PyPI Package
20
**You can run the Interference API directly from the G4F PyPI package:**
21
```python
22
from g4f.api import run_api
23
24
run_api()
25
```
26
27
28
29
### From Repository
30
Alternatively, you can run the Interference API from the cloned repository.
31
32
**Run the server with:**
33
```bash
34
g4f api
35
```
36
or
37
```bash
38
python -m g4f.api.run
39
```
40
41
42
43
## Usage with OpenAI Library
44
45
46
47
```python
48
from openai import OpenAI
49
50
client = OpenAI(
51
api_key="",
52
# Change the API base URL to the local interference API
53
base_url="http://localhost:1337/v1"
54
)
55
56
response = client.chat.completions.create(
57
model="gpt-3.5-turbo",
58
messages=[{"role": "user", "content": "write a poem about a tree"}],
59
stream=True,
60
)
61
62
if isinstance(response, dict):
63
# Not streaming
64
print(response.choices[0].message.content)
65
else:
66
# Streaming
67
for token in response:
68
content = token.choices[0].delta.content
69
if content is not None:
70
print(content, end="", flush=True)
71
```
72
73
74
75
## Usage with Requests Library
76
You can also send requests directly to the Interference API using the requests library.
77
78
**Send a POST request to `/v1/chat/completions` with the request body containing the model and other parameters:**
79
```python
80
import requests
81
82
url = "http://localhost:1337/v1/chat/completions"
83
body = {
84
"model": "gpt-3.5-turbo",
85
"stream": False,
86
"messages": [
87
{"role": "assistant", "content": "What can you do?"}
88
]
89
}
90
91
json_response = requests.post(url, json=body).json().get('choices', [])
92
93
for choice in json_response:
94
print(choice.get('message', {}).get('content', ''))
95
```
96
97
98
99
## Key Points
100
- The Interference API translates OpenAI API requests into G4F provider requests
101
- You can run it from the PyPI package or the cloned repository
102
- It supports usage with the OpenAI Python library by changing the `base_url`
103
- Direct requests can be sent to the API endpoints using libraries like `requests`
104
105
106
**_The Interference API allows easy integration of G4F with existing OpenAI-based applications and tools._**
107
108
---
109
110
[Return to Home](/)
@@ -1,16 +1,20 @@
1
1
2
# G4F - Providers and Models
2
3
4
This document provides an overview of various AI providers and models, including text generation, image generation, and vision capabilities. It aims to help users navigate the diverse landscape of AI services and choose the most suitable option for their needs.
3
5
4
## 🚀 Providers and Models
5
- [Providers](#Providers)
6
## Table of Contents
7
- [Providers](#providers)
6
8
- [Models](#models)
7
- [Text Model](#text-model)
8
- [Image Model](#image-model)
9
- [Text Models](#text-models)
10
- [Image Models](#image-models)
11
- [Vision Models](#vision-models)
12
- [Conclusion and Usage Tips](#conclusion-and-usage-tips)
9
13
10
14
---
11
#### Providers
12
|Website|Provider|Text Model|Image Model|Vision Model|Stream|Status|Auth|
13
|--|--|--|--|--|--|--|--|
15
## Providers
16
| Provider | Text Models | Image Models | Vision Models | Stream | Status | Auth |
17
|----------|-------------|--------------|---------------|--------|--------|------|
14
18
|[ai4chat.co](https://www.ai4chat.co)|`g4f.Provider.Ai4Chat`|`gpt-4`|❌|❌|✔||❌|
15
19
|[chat.ai365vip.com](https://chat.ai365vip.com)|`g4f.Provider.AI365VIP`|`gpt-3.5-turbo, gpt-4o`|❌|❌|?||❌|
16
20
|[aichatfree.info](https://aichatfree.info)|`g4f.Provider.AIChatFree`|`gemini-pro`|❌|❌|✔||❌|
@@ -101,14 +105,11 @@
101
105
|[whiterabbitneo.com](https://www.whiterabbitneo.com)|`g4f.Provider.WhiteRabbitNeo`|✔|❌|❌|?||✔|
102
106
|[you.com](https://you.com)|`g4f.Provider.You`|✔|✔|✔|✔||❌+✔|
103
107
108
## Models
104
109
105
106
107
### Models
108
#### Text Model
109
|Model|Base Provider|Provider|Website|
110
|--|--|--|-|
110
### Text Models
111
| Model | Base Provider | Providers | Website |
112
|-------|---------------|-----------|---------|
111
113
|gpt-3|OpenAI|1+ Providers|[platform.openai.com](https://platform.openai.com/docs/models/gpt-base)|
112
114
|gpt-3.5-turbo|OpenAI|5+ Providers|[platform.openai.com](https://platform.openai.com/docs/models/gpt-3-5-turbo)|
113
115
|gpt-4|OpenAI|9+ Providers|[platform.openai.com](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4)|
@@ -195,10 +196,10 @@
195
196
|german-7b|TheBloke|1+ Providers|[huggingface.co](https://huggingface.co/TheBloke/DiscoLM_German_7b_v1-GGUF)|
196
197
|tinyllama-1.1b|TinyLlama|1+ Providers|[huggingface.co](https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0)|
197
198
|cybertron-7b|TheBloke|1+ Providers|[huggingface.co](https://huggingface.co/fblgit/una-cybertron-7b-v2-bf16)|
198
### Image Model
199
|Model|Base Provider|Provider|Website|
200
|--|--|--|-|
199
200
### Image Models
201
| Model | Base Provider | Providers | Website |
202
|-------|---------------|-----------|---------|
201
203
|sdxl|Stability AI|3+ Providers|[huggingface.co](https://huggingface.co/docs/diffusers/en/using-diffusers/sdxl)|
202
204
|sd-3|Stability AI|1+ Providers|[huggingface.co](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_3)|
203
205
|playground-v2.5|Playground AI|1+ Providers|[huggingface.co](https://huggingface.co/playgroundai/playground-v2.5-1024px-aesthetic)|
@@ -218,6 +219,26 @@
218
219
|emi||1+ Providers|[]()|
219
220
|any-dark||1+ Providers|[]()|
220
221
222
### Vision Models
223
| Model | Base Provider | Providers | Website |
224
|-------|---------------|-----------|---------|
225
|gpt-4-vision|OpenAI|1+ Providers|[openai.com](https://openai.com/research/gpt-4v-system-card)|
226
|gemini-pro-vision|Google DeepMind|1+ Providers | [deepmind.google](https://deepmind.google/technologies/gemini/)|
227
|blackboxai|Blackbox AI|1+ Providers|[docs.blackbox.chat](https://docs.blackbox.chat/blackbox-ai-1)|
228
|minicpm-llama-3-v2.5|OpenBMB|1+ Providers | [huggingface.co](https://huggingface.co/openbmb/MiniCPM-Llama3-V-2_5)|
229
230
## Conclusion and Usage Tips
231
This document provides a comprehensive overview of various AI providers and models available for text generation, image generation, and vision tasks. **When choosing a provider or model, consider the following factors:**
232
1. **Availability**: Check the status of the provider to ensure it's currently active and accessible.
233
2. **Model Capabilities**: Different models excel at different tasks. Choose a model that best fits your specific needs, whether it's text generation, image creation, or vision-related tasks.
234
3. **Authentication**: Some providers require authentication, while others don't. Consider this when selecting a provider for your project.
235
4. **Streaming Support**: If real-time responses are important for your application, prioritize providers that offer streaming capabilities.
236
5. **Vision Models**: For tasks requiring image understanding or multimodal interactions, look for providers offering vision models.
237
238
Remember to stay updated with the latest developments in the AI field, as new models and providers are constantly emerging and evolving.
239
240
---
221
241
242
Last Updated: 2024-10-19
222
243
223
244
[Return to Home](/)
@@ -43,4 +43,5 @@ Install all packages and uninstall this package for disabling the webdriver:
43
43
pip uninstall undetected-chromedriver
44
44
```
45
45
46
---
46
47
[Return to Home](/)