返回提交历史
Added
docs/API_REFERENCE.md
+166
-0
Modified
docs/README.md
+10
-1
Added
docs/USAGE.md
+179
-0
XFEstudio/gpt4free
Add comprehensive documentation with usage guide and API reference
Co-authored-by: fkahdias <fkahdias@gmail.com>
ef72441e
代码差异
3 个文件
+355
-1
@@ -0,0 +1,166 @@
1
# g4f API Reference
2
3
> This document gives a **human-curated** overview of all *public* classes, functions and constants in the `g4f` package. Internal helpers (modules prefixed with an underscore or imported only for backward-compatibility) are intentionally omitted.
4
5
For detailed type information inspect the inline type hints or open the corresponding source files in your editor.
6
7
---
8
9
## Package-level exports (`import g4f`)
10
11
| Symbol | Type | Description |
12
| ------ | ---- | ----------- |
13
| `ChatCompletion` | `class` | High-level static interface for creating chat (and optionally image) completions. Mirrors the official OpenAI semantics. |
14
| `Model` | `dataclass` | Immutable description of a model + its preferred provider. Registered on import. |
15
| `ModelRegistry` | `class` | Global registry; look-up utility for `Model` instances and aliases. |
16
| `Client` | `class` | Synchronous convenience wrapper combining chat & image endpoints. |
17
| `AsyncClient` | `class` | Asynchronous variant of `Client`. |
18
| `get_cookies / set_cookies` | `function` | Persist and retrieve provider-specific cookies used during web-scraping. |
19
20
---
21
22
## 1. `ChatCompletion`
23
24
```python
25
class ChatCompletion:
26
@staticmethod
27
def create(
28
model: Union[Model, str],
29
messages: Messages,
30
provider: Union[ProviderType, str, None] = None,
31
stream: bool = False,
32
image: ImageType | None = None,
33
image_name: str | None = None,
34
ignore_working: bool = False,
35
ignore_stream: bool = False,
36
**provider_kwargs,
37
) -> str | Iterator[ChatCompletionChunk] | ChatCompletionChunk:
38
"""Generate a completion. If *stream* is *True* an iterator of chunks is returned."""
39
40
@staticmethod
41
async def create_async(...):
42
"""Asynchronous mirror of `create`. Returns either a Coroutine (non-stream) or an async iterator (stream)."""
43
```
44
45
### Behaviour
46
47
1. **Automatic provider routing** – When *provider* is `None` the best provider for the chosen *model* is selected via `models.py`.
48
2. **Proxies** – honours `G4F_PROXY` env variable if `proxy` kwarg is omitted.
49
3. **Images** – pass a file-like object or bytes via the `image` parameter to switch to *vision* mode.
50
51
### Minimal example
52
53
```python
54
from g4f import ChatCompletion
55
56
answer = ChatCompletion.create(
57
model="gpt-4", messages=[{"role": "user", "content": "Ping!"}]
58
)
59
print(answer)
60
```
61
62
---
63
64
## 2. `g4f.client` module
65
66
### `Client`
67
68
A one-stop object that contains nested service namespaces mirroring the official OpenAI Python SDK.
69
70
```python
71
client = g4f.client.Client(proxy="http://127.0.0.1:7890")
72
73
client.chat.completions.create(...)
74
client.images.generate(...)
75
```
76
77
Key attributes:
78
79
| Attribute | Type | Purpose |
80
| --------- | ---- | ------- |
81
| `chat.completions` | `Completions` | Synchronous chat endpoint. |
82
| `images` / `media` | `Images` | Image generation & variation helpers. |
83
| `models` | `ClientModels` | Convenience object for provider selection. |
84
85
### `AsyncClient`
86
87
Identical surface but all methods are `async`:
88
89
```python
90
async_client = g4f.client.AsyncClient()
91
answer = await async_client.chat.completions.create(...)
92
```
93
94
---
95
96
## 3. `g4f.models` module
97
98
### `Model`
99
Dataclass with fields:
100
101
```python
102
name: str # "gpt-4o", "llama-3-8b", ...
103
base_provider: str # human readable provider family
104
best_provider: ProviderType | IterListProvider
105
```
106
107
The file ships with **hundreds** of ready-to-use model constants (e.g. `g4f.models.gpt_4`, `llama_3_70b`, `dall_e_3`). Retrieve them dynamically via:
108
109
```python
110
from g4f.models import ModelRegistry
111
print(ModelRegistry.all_models().keys())
112
```
113
114
### `ModelRegistry` – helper methods
115
116
* `get(name)` – resolve an alias or canonical name to a `Model` instance.
117
* `list_models_by_provider(provider_name)` – filter by provider (e.g. "Together").
118
* `validate_all_models()` – sanity-check that each registered model has a provider.
119
120
---
121
122
## 4. Error classes (`g4f.errors`)
123
124
| Error | Raised when |
125
| ----- | ----------- |
126
| `StreamNotSupportedError` | You requested `stream=True` but the selected provider lacks streaming support. |
127
| `NoMediaResponseError` | No image data was returned by the provider. |
128
129
All errors ultimately inherit from `Exception`.
130
131
---
132
133
## 5. Provider ecosystem (advanced)
134
135
Providers live in the `g4f.providers` & `g4f.Provider` packages. Each provider class implements `create_function` and (optionally) `async_create_function`. When adding a new provider follow the template in `providers/types.py`.
136
137
---
138
139
## 6. Typing aliases (`g4f.typing`)
140
141
Useful public aliases:
142
143
```python
144
Messages = list[dict[str, str]]
145
ImageType = Union[str, bytes, pathlib.Path, BinaryIO]
146
CreateResult = ChatCompletion | Iterator[ChatCompletionChunk]
147
```
148
149
---
150
151
## 7. CLI entry-point (`python -m g4f`)
152
153
`python -m g4f "Your prompt here" --model gpt-4o --stream` launches the minimal CLI tool defined in `g4f/__main__.py`.
154
155
---
156
157
## 8. Debug utilities
158
159
Set the `G4F_DEBUG` environment variable to enable verbose logs from the `g4f.debug` module.
160
161
---
162
163
### Notes
164
165
* **Stability** – Public APIs follow semantic-versioning rules (see `g4f.version.__version__`). Minor & patch releases will not introduce breaking changes.
166
* **Experimental modules** (`g4f.gui`, `g4f.local`) are *not* covered by this reference and may change at any time without notice.
@@ -1 +1,10 @@
1
Link to [Documentation](https://github.com/gpt4free/gpt4free.github.io)
1
Link to [Documentation](https://github.com/gpt4free/gpt4free.github.io)
2
3
---
4
5
# Local Documentation Index
6
7
* [Usage Guide](./USAGE.md) – step-by-step examples for the most common tasks.
8
* [API Reference](./API_REFERENCE.md) – class & function level documentation.
9
10
The upstream hosted docs remain available at the link above, but the Markdown files in this folder are guaranteed to be in sync with the current commit.
@@ -0,0 +1,179 @@
1
# g4f Usage Guide
2
3
This guide provides practical, copy-paste ready examples demonstrating the most common ways to use **g4f** in your own projects.
4
5
---
6
7
## 1. Installation
8
9
```
10
pip install g4f # or install from source
11
```
12
13
> **Tip** – If you are in a PEP-668 managed environment (e.g. Debian/Ubuntu 24.04) add the `--break-system-packages` flag:
14
>
15
> ```bash
16
> pip install --break-system-packages g4f
17
> ```
18
19
---
20
21
## 2. Quick start – one-liner
22
23
```python
24
import g4f
25
26
response = g4f.ChatCompletion.create(
27
model="gpt-4o", # or any other supported model name
28
messages=[{"role": "user", "content": "Hello!"}]
29
)
30
print(response) # → "Hello! How can I help you today?"
31
```
32
33
---
34
35
## 3. Chat completions in detail
36
37
### Synchronous API
38
39
```python
40
from g4f import ChatCompletion
41
42
messages = [
43
{"role": "system", "content": "You are a concise assistant."},
44
{"role": "user", "content": "Summarise the plot of Dune in one sentence."},
45
]
46
47
result = ChatCompletion.create(
48
model="gpt-4o-mini", # model alias or full name
49
messages=messages,
50
# provider="DeepInfraChat", # optional – override automatic routing
51
stream=False # default: return single string
52
)
53
print(result.content)
54
```
55
56
### Streaming responses
57
58
```python
59
for chunk in ChatCompletion.create(
60
model="gpt-4o-mini", messages=messages, stream=True
61
):
62
print(chunk, end="", flush=True) # each chunk is a ChatCompletionChunk
63
```
64
65
### Asynchronous API
66
67
```python
68
import asyncio
69
from g4f import ChatCompletion
70
71
async def main():
72
async for chunk in ChatCompletion.create_async(
73
model="gpt-4", messages=messages, stream=True
74
):
75
print(chunk)
76
77
asyncio.run(main())
78
```
79
80
---
81
82
## 4. High–level clients
83
84
The `Client` and `AsyncClient` classes wrap chat, image and (soon) voice endpoints in a single object.
85
86
```python
87
from g4f.client import Client, AsyncClient
88
89
client = Client(proxy="http://127.0.0.1:7890")
90
91
# Chat
92
answer = client.chat.completions.create(
93
messages="Why is the sky blue?"
94
)
95
print(answer.content)
96
97
# Images (sync)
98
image_resp = client.images.generate("A cyber-punk cityscape at night")
99
image_resp.save("cyberpunk.png")
100
101
# Asynchronous variant
102
async def run():
103
async_client = AsyncClient()
104
answer = await async_client.chat.completions.create(
105
messages="List the first 5 prime numbers"
106
)
107
print(answer.content)
108
109
import asyncio; asyncio.run(run())
110
```
111
112
---
113
114
## 5. Image generation
115
116
```python
117
img = client.images.generate(
118
prompt="A photo-realistic cat wearing sunglasses",
119
model="dall-e-3" # or leave blank for automatic provider selection
120
)
121
122
# Access the image as Pillow object
123
img_pil = img.images[0]
124
img_pil.show()
125
126
# Or save to disk
127
img.save_all("output/")
128
```
129
130
---
131
132
## 6. Model registry utilities
133
134
```python
135
from g4f.models import ModelRegistry
136
137
print("All models:", ModelRegistry.all_models().keys())
138
print("Aliases for Llama providers:", ModelRegistry.list_models_by_provider("Together"))
139
```
140
141
---
142
143
## 7. Environment variables
144
145
• `G4F_PROXY` – default HTTP(S) proxy used when `proxy` is not supplied.
146
147
• `G4F_PROVIDER_TIMEOUT` – override default request timeout (in seconds).
148
149
---
150
151
## 8. Error handling basics
152
153
```python
154
from g4f.errors import StreamNotSupportedError
155
156
try:
157
ChatCompletion.create(model="some-model", messages=[], stream=True)
158
except StreamNotSupportedError:
159
print("Selected provider does not support streaming")
160
```
161
162
---
163
164
## 9. CLI usage
165
166
The project ships with an experimental CLI:
167
168
```bash
169
g4f "Translate 'Good morning' to Spanish" --model gpt-4o
170
```
171
172
Run `g4f --help` to see the full list of flags.
173
174
---
175
176
## 10. Next steps
177
178
* Dive into the [API reference](./API_REFERENCE.md) for every public class and function.
179
* Read the [Contributing guide](../CONTRIBUTING.md) if you want to add a new provider or model.