返回提交历史
Modified
docker-compose-slim.yml
+2
-2
Modified
docs/async_client.md
+1
-33
Modified
docs/client.md
+6
-48
Modified
g4f/api/__init__.py
+1
-1
Modified
g4f/client/__init__.py
+10
-10
Modified
g4f/client/stubs.py
+21
-21
XFEstudio/gpt4free
Use pydantic construct and `dict` instead of model_construct and model_dump
d6b18c0f
代码差异
6 个文件
+41
-115
@@ -3,7 +3,7 @@ version: '3'
3
3
services:
4
4
g4f-gui:
5
5
container_name: g4f-gui
6
image: hlohaus789/g4f:slim
6
image: hlohaus789/g4f:latest-slim
7
7
build:
8
8
context: .
9
9
dockerfile: docker/Dockerfile-slim
@@ -14,7 +14,7 @@ services:
14
14
- '8080:8080'
15
15
g4f-api:
16
16
container_name: g4f-api
17
image: hlohaus789/g4f:slim
17
image: hlohaus789/g4f:latest-slim
18
18
build:
19
19
context: .
20
20
dockerfile: docker/Dockerfile-slim
@@ -2,7 +2,6 @@
2
2
# G4F - AsyncClient API Guide
3
3
The G4F AsyncClient 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.
4
4
5
6
5
## Compatibility Note
7
6
The G4F AsyncClient API is designed to be compatible with the OpenAI API, making it easy for developers familiar with OpenAI's interface to transition to G4F.
8
7
@@ -24,8 +23,6 @@ The G4F AsyncClient API is designed to be compatible with the OpenAI API, making
24
23
- [Rate Limiting and API Usage](#rate-limiting-and-api-usage)
25
24
- [Conclusion](#conclusion)
26
25
27
28
29
26
## Introduction
30
27
The G4F AsyncClient 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 AsyncClient API.
31
28
@@ -37,8 +34,6 @@ The G4F AsyncClient API is an asynchronous version of the standard G4F Client AP
37
34
- **Non-Streaming Responses**: Generate complete responses in a single call.
38
35
- **Image Generation and Vision Models**: Support for image-related tasks.
39
36
40
41
42
37
## Getting Started
43
38
### Initializing the AsyncClient
44
39
**To use the G4F `AsyncClient`, create a new instance:**
@@ -53,7 +48,6 @@ client = AsyncClient(
53
48
)
54
49
```
55
50
56
57
51
## Creating Chat Completions
58
52
**Here’s an improved example of creating chat completions:**
59
53
```python
@@ -75,7 +69,6 @@ response = await client.chat.completions.create(
75
69
- Disables streaming for a complete response
76
70
77
71
You can adjust these parameters based on your specific needs.
78
79
72
80
73
### Configuration
81
74
**Configure the `AsyncClient` with additional settings:**
@@ -87,8 +80,6 @@ client = AsyncClient(
87
80
)
88
81
```
89
82
90
91
92
83
## Usage Examples
93
84
### Text Completions
94
85
**Generate text completions using the ChatCompletions endpoint:**
@@ -114,8 +105,6 @@ async def main():
114
105
asyncio.run(main())
115
106
```
116
107
117
118
119
108
### Streaming Completions
120
109
**Process responses incrementally as they are generated:**
121
110
```python
@@ -143,8 +132,6 @@ async def main():
143
132
asyncio.run(main())
144
133
```
145
134
146
147
148
135
### Using a Vision Model
149
136
**Analyze an image and generate a description:**
150
137
```python
@@ -176,8 +163,6 @@ async def main():
176
163
asyncio.run(main())
177
164
```
178
165
179
180
181
166
### Image Generation
182
167
**Generate images using a specified prompt:**
183
168
```python
@@ -198,8 +183,6 @@ async def main():
198
183
asyncio.run(main())
199
184
```
200
185
201
202
203
186
#### Base64 Response Format
204
187
```python
205
188
import asyncio
@@ -220,8 +203,6 @@ async def main():
220
203
asyncio.run(main())
221
204
```
222
205
223
224
225
206
### Concurrent Tasks with asyncio.gather
226
207
**Execute multiple tasks concurrently:**
227
208
```python
@@ -260,8 +241,6 @@ async def main():
260
241
asyncio.run(main())
261
242
```
262
243
263
264
265
244
## Available Models and Providers
266
245
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:**
267
246
@@ -274,8 +253,6 @@ The G4F AsyncClient supports a wide range of AI models and providers, allowing y
274
253
- Claude (Anthropic)
275
254
- And more...
276
255
277
278
279
256
### Providers
280
257
- OpenAI
281
258
- Google (for Gemini)
@@ -283,7 +260,6 @@ The G4F AsyncClient supports a wide range of AI models and providers, allowing y
283
260
- Microsoft Copilot
284
261
- Custom providers
285
262
286
287
263
**To use a specific model or provider, specify it when creating the client or in the API call:**
288
264
```python
289
265
client = AsyncClient(provider=g4f.Provider.OpenaiChat)
@@ -302,8 +278,6 @@ response = await client.chat.completions.create(
302
278
)
303
279
```
304
280
305
306
307
281
## Error Handling and Best Practices
308
282
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:**
309
283
@@ -342,8 +316,6 @@ async def make_api_call():
342
316
pass
343
317
```
344
318
345
346
347
319
## Rate Limiting and API Usage
348
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:
349
321
@@ -361,8 +333,6 @@ async def make_api_call():
361
333
pass
362
334
```
363
335
364
365
366
336
2. **Monitor your API usage and implement logging:**
367
337
```python
368
338
import logging
@@ -378,8 +348,6 @@ async def make_api_call():
378
348
logger.error(f"API call failed: {e}")
379
349
```
380
350
381
382
383
351
3. **Use caching to reduce API calls for repeated queries:**
384
352
```python
385
353
from functools import lru_cache
@@ -397,4 +365,4 @@ Remember to handle errors gracefully, implement rate limiting, and monitor your
397
365
398
366
---
399
367
400
[Return to Home](/)
368
[Return to Home](/)
@@ -1,6 +1,5 @@
1
1
2
2
# G4F Client API Guide
3
4
3
5
4
## Table of Contents
6
5
- [Introduction](#introduction)
@@ -16,12 +15,9 @@
16
15
- [Creating Image Variations](#creating-image-variations)
17
16
- [Advanced Usage](#advanced-usage)
18
17
- [Using a List of Providers with RetryProvider](#using-a-list-of-providers-with-retryprovider)
19
- [Using GeminiProVision](#using-geminiprovision)
20
18
- [Using a Vision Model](#using-a-vision-model)
21
19
- [Command-line Chat Program](#command-line-chat-program)
22
20
23
24
25
21
## Introduction
26
22
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.
27
23
@@ -34,15 +30,11 @@ Welcome to the G4F Client API, a cutting-edge tool for seamlessly integrating ad
34
30
from openai import OpenAI
35
31
```
36
32
37
38
39
33
**New Import:**
40
34
```python
41
35
from g4f.client import Client as OpenAI
42
36
```
43
37
44
45
46
38
The G4F Client preserves the same familiar API interface as OpenAI, ensuring a smooth transition process.
47
39
48
40
## Initializing the Client
@@ -79,7 +71,6 @@ response = client.chat.completions.create(
79
71
- Disables streaming for a complete response
80
72
81
73
You can adjust these parameters based on your specific needs.
82
83
74
84
75
## Configuration
85
76
**You can set an `api_key` for your provider in the client and define a proxy for all outgoing requests:**
@@ -93,8 +84,6 @@ client = Client(
93
84
)
94
85
```
95
86
96
97
98
87
## Usage Examples
99
88
### Text Completions
100
89
**Generate text completions using the `ChatCompletions` endpoint:**
@@ -117,8 +106,6 @@ response = client.chat.completions.create(
117
106
print(response.choices[0].message.content)
118
107
```
119
108
120
121
122
109
### Streaming Completions
123
110
**Process responses incrementally as they are generated:**
124
111
```python
@@ -142,8 +129,6 @@ for chunk in stream:
142
129
print(chunk.choices[0].delta.content or "", end="")
143
130
```
144
131
145
146
147
132
### Image Generation
148
133
**Generate images using a specified prompt:**
149
134
```python
@@ -162,7 +147,6 @@ image_url = response.data[0].url
162
147
print(f"Generated image URL: {image_url}")
163
148
```
164
149
165
166
150
#### Base64 Response Format
167
151
```python
168
152
from g4f.client import Client
@@ -179,8 +163,6 @@ base64_text = response.data[0].b64_json
179
163
print(base64_text)
180
164
```
181
165
182
183
184
166
### Creating Image Variations
185
167
**Create variations of an existing image:**
186
168
```python
@@ -202,8 +184,6 @@ image_url = response.data[0].url
202
184
print(f"Generated image URL: {image_url}")
203
185
```
204
186
205
206
207
187
## Advanced Usage
208
188
209
189
### Using a List of Providers with RetryProvider
@@ -231,47 +211,25 @@ response = client.chat.completions.create(
231
211
232
212
print(response.choices[0].message.content)
233
213
```
234
235
214
236
### Using GeminiProVision
215
### Using a Vision Model
216
**Analyze an image and generate a description:**
237
217
```python
218
import g4f
219
import requests
220
238
221
from g4f.client import Client
239
222
from g4f.Provider.GeminiPro import GeminiPro
240
223
224
# Initialize the GPT client with the desired provider and api key
241
225
client = Client(
242
226
api_key="your_api_key_here",
243
227
provider=GeminiPro
244
228
)
245
229
246
response = client.chat.completions.create(
247
model="gemini-pro-vision",
248
messages=[
249
{
250
"role": "user",
251
"content": "What are on this image?"
252
}
253
],
254
image=open("docs/waterfall.jpeg", "rb")
255
)
256
257
print(response.choices[0].message.content)
258
```
259
260
261
### Using a Vision Model
262
**Analyze an image and generate a description:**
263
```python
264
import g4f
265
import requests
266
from g4f.client import Client
267
268
230
image = requests.get("https://raw.githubusercontent.com/xtekky/gpt4free/refs/heads/main/docs/cat.jpeg", stream=True).raw
269
231
# Or: image = open("docs/cat.jpeg", "rb")
270
232
271
client = Client(
272
provider=CopilotAccount
273
)
274
275
233
response = client.chat.completions.create(
276
234
model=g4f.models.default,
277
235
messages=[
@@ -305,7 +305,7 @@ class Api:
305
305
"model": AppConfig.model,
306
306
"provider": AppConfig.provider,
307
307
"proxy": AppConfig.proxy,
308
**config.model_dump(exclude_none=True),
308
**config.dict(exclude_none=True),
309
309
**{
310
310
"conversation_id": None,
311
311
"return_conversation": return_conversation,
@@ -74,7 +74,7 @@ def iter_response(
74
74
finish_reason = "stop"
75
75
76
76
if stream:
77
yield ChatCompletionChunk.model_construct(chunk, None, completion_id, int(time.time()))
77
yield ChatCompletionChunk.construct(chunk, None, completion_id, int(time.time()))
78
78
79
79
if finish_reason is not None:
80
80
break
@@ -84,12 +84,12 @@ def iter_response(
84
84
finish_reason = "stop" if finish_reason is None else finish_reason
85
85
86
86
if stream:
87
yield ChatCompletionChunk.model_construct(None, finish_reason, completion_id, int(time.time()))
87
yield ChatCompletionChunk.construct(None, finish_reason, completion_id, int(time.time()))
88
88
else:
89
89
if response_format is not None and "type" in response_format:
90
90
if response_format["type"] == "json_object":
91
91
content = filter_json(content)
92
yield ChatCompletion.model_construct(content, finish_reason, completion_id, int(time.time()))
92
yield ChatCompletion.construct(content, finish_reason, completion_id, int(time.time()))
93
93
94
94
# Synchronous iter_append_model_and_provider function
95
95
def iter_append_model_and_provider(response: ChatCompletionResponseType) -> ChatCompletionResponseType:
@@ -138,7 +138,7 @@ async def async_iter_response(
138
138
finish_reason = "stop"
139
139
140
140
if stream:
141
yield ChatCompletionChunk.model_construct(chunk, None, completion_id, int(time.time()))
141
yield ChatCompletionChunk.construct(chunk, None, completion_id, int(time.time()))
142
142
143
143
if finish_reason is not None:
144
144
break
@@ -146,12 +146,12 @@ async def async_iter_response(
146
146
finish_reason = "stop" if finish_reason is None else finish_reason
147
147
148
148
if stream:
149
yield ChatCompletionChunk.model_construct(None, finish_reason, completion_id, int(time.time()))
149
yield ChatCompletionChunk.construct(None, finish_reason, completion_id, int(time.time()))
150
150
else:
151
151
if response_format is not None and "type" in response_format:
152
152
if response_format["type"] == "json_object":
153
153
content = filter_json(content)
154
yield ChatCompletion.model_construct(content, finish_reason, completion_id, int(time.time()))
154
yield ChatCompletion.construct(content, finish_reason, completion_id, int(time.time()))
155
155
finally:
156
156
await safe_aclose(response)
157
157
@@ -419,13 +419,13 @@ class Images:
419
419
if response_format == "b64_json":
420
420
with open(os.path.join(images_dir, os.path.basename(image_file)), "rb") as file:
421
421
image_data = base64.b64encode(file.read()).decode()
422
return Image.model_construct(url=image_file, b64_json=image_data, revised_prompt=response.alt)
423
return Image.model_construct(url=image_file, revised_prompt=response.alt)
422
return Image.construct(url=image_file, b64_json=image_data, revised_prompt=response.alt)
423
return Image.construct(url=image_file, revised_prompt=response.alt)
424
424
images = await asyncio.gather(*[process_image_item(image) for image in images])
425
425
else:
426
images = [Image.model_construct(url=image, revised_prompt=response.alt) for image in response.get_list()]
426
images = [Image.construct(url=image, revised_prompt=response.alt) for image in response.get_list()]
427
427
last_provider = get_last_provider(True)
428
return ImagesResponse.model_construct(
428
return ImagesResponse.construct(
429
429
images,
430
430
model=last_provider.get("model") if model is None else model,
431
431
provider=last_provider.get("name") if provider is None else provider
@@ -10,7 +10,7 @@ try:
10
10
except ImportError:
11
11
class BaseModel():
12
12
@classmethod
13
def model_construct(cls, **data):
13
def construct(cls, **data):
14
14
new = cls()
15
15
for key, value in data.items():
16
16
setattr(new, key, value)
@@ -28,21 +28,21 @@ class ChatCompletionChunk(BaseModel):
28
28
choices: List[ChatCompletionDeltaChoice]
29
29
30
30
@classmethod
31
def model_construct(
31
def construct(
32
32
cls,
33
33
content: str,
34
34
finish_reason: str,
35
35
completion_id: str = None,
36
36
created: int = None
37
37
):
38
return super().model_construct(
38
return super().construct(
39
39
id=f"chatcmpl-{completion_id}" if completion_id else None,
40
40
object="chat.completion.cunk",
41
41
created=created,
42
42
model=None,
43
43
provider=None,
44
choices=[ChatCompletionDeltaChoice.model_construct(
45
ChatCompletionDelta.model_construct(content),
44
choices=[ChatCompletionDeltaChoice.construct(
45
ChatCompletionDelta.construct(content),
46
46
finish_reason
47
47
)]
48
48
)
@@ -52,8 +52,8 @@ class ChatCompletionMessage(BaseModel):
52
52
content: str
53
53
54
54
@classmethod
55
def model_construct(cls, content: str):
56
return super().model_construct(role="assistant", content=content)
55
def construct(cls, content: str):
56
return super().construct(role="assistant", content=content)
57
57
58
58
class ChatCompletionChoice(BaseModel):
59
59
index: int
@@ -61,8 +61,8 @@ class ChatCompletionChoice(BaseModel):
61
61
finish_reason: str
62
62
63
63
@classmethod
64
def model_construct(cls, message: ChatCompletionMessage, finish_reason: str):
65
return super().model_construct(index=0, message=message, finish_reason=finish_reason)
64
def construct(cls, message: ChatCompletionMessage, finish_reason: str):
65
return super().construct(index=0, message=message, finish_reason=finish_reason)
66
66
67
67
class ChatCompletion(BaseModel):
68
68
id: str
@@ -78,21 +78,21 @@ class ChatCompletion(BaseModel):
78
78
}])
79
79
80
80
@classmethod
81
def model_construct(
81
def construct(
82
82
cls,
83
83
content: str,
84
84
finish_reason: str,
85
85
completion_id: str = None,
86
86
created: int = None
87
87
):
88
return super().model_construct(
88
return super().construct(
89
89
id=f"chatcmpl-{completion_id}" if completion_id else None,
90
90
object="chat.completion",
91
91
created=created,
92
92
model=None,
93
93
provider=None,
94
choices=[ChatCompletionChoice.model_construct(
95
ChatCompletionMessage.model_construct(content),
94
choices=[ChatCompletionChoice.construct(
95
ChatCompletionMessage.construct(content),
96
96
finish_reason
97
97
)],
98
98
usage={
@@ -107,8 +107,8 @@ class ChatCompletionDelta(BaseModel):
107
107
content: str
108
108
109
109
@classmethod
110
def model_construct(cls, content: Optional[str]):
111
return super().model_construct(role="assistant", content=content)
110
def construct(cls, content: Optional[str]):
111
return super().construct(role="assistant", content=content)
112
112
113
113
class ChatCompletionDeltaChoice(BaseModel):
114
114
index: int
@@ -116,8 +116,8 @@ class ChatCompletionDeltaChoice(BaseModel):
116
116
finish_reason: Optional[str]
117
117
118
118
@classmethod
119
def model_construct(cls, delta: ChatCompletionDelta, finish_reason: Optional[str]):
120
return super().model_construct(index=0, delta=delta, finish_reason=finish_reason)
119
def construct(cls, delta: ChatCompletionDelta, finish_reason: Optional[str]):
120
return super().construct(index=0, delta=delta, finish_reason=finish_reason)
121
121
122
122
class Image(BaseModel):
123
123
url: Optional[str]
@@ -125,8 +125,8 @@ class Image(BaseModel):
125
125
revised_prompt: Optional[str]
126
126
127
127
@classmethod
128
def model_construct(cls, url: str = None, b64_json: str = None, revised_prompt: str = None):
129
return super().model_construct(**filter_none(
128
def construct(cls, url: str = None, b64_json: str = None, revised_prompt: str = None):
129
return super().construct(**filter_none(
130
130
url=url,
131
131
b64_json=b64_json,
132
132
revised_prompt=revised_prompt
@@ -139,10 +139,10 @@ class ImagesResponse(BaseModel):
139
139
created: int
140
140
141
141
@classmethod
142
def model_construct(cls, data: List[Image], created: int = None, model: str = None, provider: str = None):
142
def construct(cls, data: List[Image], created: int = None, model: str = None, provider: str = None):
143
143
if created is None:
144
144
created = int(time())
145
return super().model_construct(
145
return super().construct(
146
146
data=data,
147
147
model=model,
148
148
provider=provider,