XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

Update docs / readme, Improve Gemini auth

0a0698c7
Heiner Lohaus <hlohaus@users.noreply.github.com>
提交于

代码差异

8 个文件 +250 -189
Modified README.md +47 -160
@@ -100,72 +100,43 @@ or set the api base in your client to: [http://localhost:1337/v1](http://localho
100 100
101 101 ##### Install using pypi:
102 102
103 Install all supported tools / all used packages:
104 103 ```
105 104 pip install -U g4f[all]
106 105 ```
107 106
108 Or use: [Partially Requirements](/docs/requirements.md)
107 Or use partial requirements.
109 108
109 See: [/docs/requirements](/docs/requirements.md)
110 110
111 111 ##### Install from source:
112 112
113 1. Clone the GitHub repository:
113 See: [/docs/git](/docs/git.md)
114 114
115 ```
116 git clone https://github.com/xtekky/gpt4free.git
117 ```
118
119 2. Navigate to the project directory:
120
121 ```
122 cd gpt4free
123 ```
124 115
125 3. (Recommended) Create a Python virtual environment:
126 You can follow the [Python official documentation](https://docs.python.org/3/tutorial/venv.html) for virtual environments.
127
128
129 ```
130 python3 -m venv venv
131 ```
116 ##### Install using Docker
132 117
133 4. Activate the virtual environment:
134 - On Windows:
135 ```
136 .\venv\Scripts\activate
137 ```
138 - On macOS and Linux:
139 ```
140 source venv/bin/activate
141 ```
142 5. Install minimum requirements:
118 See: [/docs/docker](/docs/docker.md)
143 119
144 ```
145 pip install -r requirements-min.txt
146 ```
147 120
148 6. Or install all used Python packages from `requirements.txt`:
121 ## 💡 Usage
149 122
150 ```
151 pip install -r requirements.txt
152 ```
123 #### Text Generation
124 **with Python**
153 125
154 7. Create a `test.py` file in the root folder and start using the repo, further Instructions are below
126 ```python
127 from g4f.client import Client
155 128
156 ```py
157 import g4f
158 ...
129 client = Client()
130 response = client.chat.completions.create(
131 model="gpt-3.5-turbo",
132 messages=[{"role": "user", "content": "Say this is a test"}],
133 ...
134 )
135 print(response.choices[0].message.content)
159 136 ```
160 137
161 ##### Install using Docker
162
163 Or use: [Build Docker](/docs/docker.md)
164
165
166 ## 💡 Usage
167
168 138 #### Image Generation
139 **with Python**
169 140
170 141 ```python
171 142 from g4f.client import Client
@@ -182,9 +153,7 @@ Result:
182 153
183 154 [![Image with cat](/docs/cat.jpeg)](/docs/client.md)
184 155
185 #### Text Generation
186
187 and more:
156 **See also for Python:**
188 157
189 158 - [Documentation for new Client](/docs/client.md)
190 159 - [Documentation for leagcy API](/docs/leagcy.md)
@@ -192,19 +161,31 @@ and more:
192 161
193 162 #### Web UI
194 163
195 To start the web interface, type the following codes in the command line.
164 To start the web interface, type the following codes in python:
196 165
197 166 ```python
198 167 from g4f.gui import run_gui
199 168 run_gui()
200 169 ```
170 or type in command line:
171 ```bash
172 python -m g4f.cli gui -port 8080 -debug
173 ```
174
175 ### Interference API
176
177 You can use the Interference API to serve other OpenAI integrations with G4F.
178
179 See: [/docs/interference](/docs/interference.md)
180
181 ### Configuration
201 182
202 183 ##### Cookies / Access Token
203 184
204 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:
185 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 before you run G4F:
205 186
206 187 ```python
207 from g4f import set_cookies
188 from g4f.cookies import set_cookies
208 189
209 190 set_cookies(".bing.com", {
210 191 "_U": "cookie value"
@@ -212,124 +193,30 @@ set_cookies(".bing.com", {
212 193 set_cookies("chat.openai.com", {
213 194 "access_token": "token value"
214 195 })
196 set_cookies(".google.com", {
197 "__Secure-1PSID": "cookie value"
198 })
215 199
216 from g4f.gui import run_gui
217 run_gui()
218 ```
219
220 Alternatively, g4f reads the cookies with “browser_cookie3” from your browser
221 or it starts a browser instance with selenium "webdriver" for logging in.
222 If you use the pip package, you have to install “browser_cookie3” or "webdriver" by yourself.
223
224 ```bash
225 pip install browser_cookie3
226 pip install g4f[webdriver]
200 ...
227 201 ```
228 202
229 ##### Proxy and Timeout Support
203 Alternatively, G4F reads the cookies with `browser_cookie3` from your browser
204 or it starts a browser instance with selenium `webdriver` for logging in.
230 205
231 All providers support specifying a proxy and increasing timeout in the create functions.
206 ##### Using Proxy
232 207
233 ```python
234 import g4f
208 If you want to hide or change your IP address for the providers, you can set a proxy globally via an environment variable:
235 209
236 response = g4f.ChatCompletion.create(
237 model=g4f.models.default,
238 messages=[{"role": "user", "content": "Hello"}],
239 proxy="http://host:port",
240 # or socks5://user:pass@host:port
241 timeout=120, # in secs
242 )
243
244 print(f"Result:", response)
245 ```
246
247 You can also set a proxy globally via an environment variable:
248
249 ```sh
210 - On macOS and Linux:
211 ```bash
250 212 export G4F_PROXY="http://host:port"
251 213 ```
252 214
253 ### Interference openai-proxy API (Use with openai python package)
254
255 #### Run interference API from PyPi package
256
257 ```python
258 from g4f.api import run_api
259
260 run_api()
261 ```
262
263 #### Run interference API from repo
264
265 If you want to use the embedding function, you need to get a Hugging Face token. You can get one at [Hugging Face Tokens](https://huggingface.co/settings/tokens). Make sure your role is set to write. If you have your token, just use it instead of the OpenAI api-key.
266
267 Run server:
268
269 ```sh
270 g4f api
271 ```
272
273 or
274
275 ```sh
276 python -m g4f.api.run
277 ```
278
279 ```python
280 from openai import OpenAI
281
282 client = OpenAI(
283 # Set your Hugging Face token as the API key if you use embeddings
284 api_key="YOUR_HUGGING_FACE_TOKEN",
285
286 # Set the API base URL if needed, e.g., for a local development environment
287 base_url="http://localhost:1337/v1"
288 )
289
290
291 def main():
292 chat_completion = client.chat.completions.create(
293 model="gpt-3.5-turbo",
294 messages=[{"role": "user", "content": "write a poem about a tree"}],
295 stream=True,
296 )
297
298 if isinstance(chat_completion, dict):
299 # Not streaming
300 print(chat_completion.choices[0].message.content)
301 else:
302 # Streaming
303 for token in chat_completion:
304 content = token.choices[0].delta.content
305 if content is not None:
306 print(content, end="", flush=True)
307
308
309 if __name__ == "__main__":
310 main()
311 ```
312
313 ## API usage (POST)
314 #### Chat completions
315 Send the POST request to /v1/chat/completions with body containing the `model` method. This example uses python with requests library:
316 ```python
317 import requests
318 url = "http://localhost:1337/v1/chat/completions"
319 body = {
320 "model": "gpt-3.5-turbo-16k",
321 "stream": False,
322 "messages": [
323 {"role": "assistant", "content": "What can you do?"}
324 ]
325 }
326 json_response = requests.post(url, json=body).json().get('choices', [])
327
328 for choice in json_response:
329 print(choice.get('message', {}).get('content', ''))
215 - On Windows:
216 ```bash
217 set G4F_PROXY=http://host:port
330 218 ```
331 219
332
333 220 ## 🚀 Providers and Models
334 221
335 222 ### GPT-4
Modified docs/client.md +12 -0
@@ -43,11 +43,23 @@ client = Client(
43 43
44 44 You can use the `ChatCompletions` endpoint to generate text completions as follows:
45 45
46 ```python
47 response = client.chat.completions.create(
48 model="gpt-3.5-turbo",
49 messages=[{"role": "user", "content": "Say this is a test"}],
50 ...
51 )
52 print(response.choices[0].message.content)
53 ```
54
55 Also streaming are supported:
56
46 57 ```python
47 58 stream = client.chat.completions.create(
48 59 model="gpt-4",
49 60 messages=[{"role": "user", "content": "Say this is a test"}],
50 61 stream=True,
62 ...
51 63 )
52 64 for chunk in stream:
53 65 if chunk.choices[0].delta.content:
Modified docs/docker.md +9 -10
@@ -1,38 +1,37 @@
1 ### G4F - Docker
1 ### G4F - Docker Setup
2 2
3 If you have Docker installed, you can easily set up and run the project without manually installing dependencies.
4
5 1. First, ensure you have both Docker and Docker Compose installed.
3 Easily set up and run the G4F project using Docker without the hassle of manual dependency installation.
6 4
5 1. **Prerequisites:**
7 6 - [Install Docker](https://docs.docker.com/get-docker/)
8 7 - [Install Docker Compose](https://docs.docker.com/compose/install/)
9 8
10 2. Clone the GitHub repo:
9 2. **Clone the Repository:**
11 10
12 11 ```bash
13 12 git clone https://github.com/xtekky/gpt4free.git
14 13 ```
15 14
16 3. Navigate to the project directory:
15 3. **Navigate to the Project Directory:**
17 16
18 17 ```bash
19 18 cd gpt4free
20 19 ```
21 20
22 4. Build the Docker image:
21 4. **Build the Docker Image:**
23 22
24 23 ```bash
25 24 docker pull selenium/node-chrome
26 25 docker-compose build
27 26 ```
28 27
29 5. Start the service using Docker Compose:
28 5. **Start the Service:**
30 29
31 30 ```bash
32 31 docker-compose up
33 32 ```
34 33
35 Your server will now be running at `http://localhost:1337`. You can interact with the API or run your tests as you would normally.
34 Your server will now be accessible at `http://localhost:1337`. Interact with the API or run tests as usual.
36 35
37 36 To stop the Docker containers, simply run:
38 37
@@ -41,6 +40,6 @@ docker-compose down
41 40 ```
42 41
43 42 > [!Note]
44 > 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`.
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`.
45 44
46 45 [Return to Home](/)
Added docs/git.md +66 -0
@@ -0,0 +1,66 @@
1 ### G4F - Installation Guide
2
3 Follow these steps to install G4F from the source code:
4
5 1. **Clone the Repository:**
6
7 ```bash
8 git clone https://github.com/xtekky/gpt4free.git
9 ```
10
11 2. **Navigate to the Project Directory:**
12
13 ```bash
14 cd gpt4free
15 ```
16
17 3. **(Optional) Create a Python Virtual Environment:**
18
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.
20
21 ```bash
22 python3 -m venv venv
23 ```
24
25 4. **Activate the Virtual Environment:**
26
27 - On Windows:
28
29 ```bash
30 .\venv\Scripts\activate
31 ```
32
33 - On macOS and Linux:
34
35 ```bash
36 source venv/bin/activate
37 ```
38
39 5. **Install Minimum Requirements:**
40
41 Install the minimum required packages:
42
43 ```bash
44 pip install -r requirements-min.txt
45 ```
46
47 6. **Or Install All Packages from `requirements.txt`:**
48
49 If you prefer, you can install all packages listed in `requirements.txt`:
50
51 ```bash
52 pip install -r requirements.txt
53 ```
54
55 7. **Start Using the Repository:**
56
57 You can now create Python scripts and utilize the G4F functionalities. Here's a basic example:
58
59 Create a `test.py` file in the root folder and start using the repository:
60
61 ```python
62 import g4f
63 # Your code here
64 ```
65
66 [Return to Home](/)
Added docs/interference.md +69 -0
@@ -0,0 +1,69 @@
1 ### Interference openai-proxy API
2
3 #### Run interference API from PyPi package
4
5 ```python
6 from g4f.api import run_api
7
8 run_api()
9 ```
10
11 #### Run interference API from repo
12
13 Run server:
14
15 ```sh
16 g4f api
17 ```
18
19 or
20
21 ```sh
22 python -m g4f.api.run
23 ```
24
25 ```python
26 from openai import OpenAI
27
28 client = OpenAI(
29 api_key="",
30 # Change the API base URL to the local interference API
31 base_url="http://localhost:1337/v1"
32 )
33
34 response = client.chat.completions.create(
35 model="gpt-3.5-turbo",
36 messages=[{"role": "user", "content": "write a poem about a tree"}],
37 stream=True,
38 )
39
40 if isinstance(response, dict):
41 # Not streaming
42 print(response.choices[0].message.content)
43 else:
44 # Streaming
45 for token in response:
46 content = token.choices[0].delta.content
47 if content is not None:
48 print(content, end="", flush=True)
49 ```
50
51 #### API usage (POST)
52 Send the POST request to /v1/chat/completions with body containing the `model` method. This example uses python with requests library:
53 ```python
54 import requests
55 url = "http://localhost:1337/v1/chat/completions"
56 body = {
57 "model": "gpt-3.5-turbo-16k",
58 "stream": False,
59 "messages": [
60 {"role": "assistant", "content": "What can you do?"}
61 ]
62 }
63 json_response = requests.post(url, json=body).json().get('choices', [])
64
65 for choice in json_response:
66 print(choice.get('message', {}).get('content', ''))
67 ```
68
69 [Return to Home](/)
Modified docs/leagcy.md +18 -0
@@ -179,4 +179,22 @@ async def run_all():
179 179 asyncio.run(run_all())
180 180 ```
181 181
182 ##### Proxy and Timeout Support
183
184 All providers support specifying a proxy and increasing timeout in the create functions.
185
186 ```python
187 import g4f
188
189 response = g4f.ChatCompletion.create(
190 model=g4f.models.default,
191 messages=[{"role": "user", "content": "Hello"}],
192 proxy="http://host:port",
193 # or socks5://user:pass@host:port
194 timeout=120, # in secs
195 )
196
197 print(f"Result:", response)
198 ```
199
182 200 [Return to Home](/)
Modified docs/requirements.md +7 -3
@@ -6,15 +6,19 @@ You can install requirements partially or completely. So G4F can be used as you
6 6
7 7 #### Options
8 8
9 Install required packages for the OpenaiChat provider:
9 Install g4f with all possible dependencies:
10 ```
11 pip install -U g4f[all]
12 ```
13 Or install only g4f and the required packages for the OpenaiChat provider:
10 14 ```
11 15 pip install -U g4f[openai]
12 16 ```
13 Install required packages for the interference api:
17 Install required packages for the Interference API:
14 18 ```
15 19 pip install -U g4f[api]
16 20 ```
17 Install required packages for the web interface:
21 Install required packages for the Web UI:
18 22 ```
19 23 pip install -U g4f[gui]
20 24 ```
Modified g4f/Provider/needs_auth/Gemini.py +22 -16
@@ -50,7 +50,6 @@ class Gemini(AsyncGeneratorProvider):
50 50 url = "https://gemini.google.com"
51 51 needs_auth = True
52 52 working = True
53 supports_stream = False
54 53
55 54 @classmethod
56 55 async def create_async_generator(
@@ -64,10 +63,9 @@ class Gemini(AsyncGeneratorProvider):
64 63 **kwargs
65 64 ) -> AsyncResult:
66 65 prompt = format_prompt(messages)
67
68 if not cookies:
69 cookies = get_cookies(".google.com", False, True)
70 if "__Secure-1PSID" not in cookies or "__Secure-1PSIDCC" not in cookies:
66 cookies = cookies if cookies else get_cookies(".google.com", False, True)
67 snlm0e = await cls.fetch_snlm0e(cookies, proxy) if cookies else None
68 if not snlm0e:
71 69 driver = None
72 70 try:
73 71 driver = get_browser(proxy=proxy)
@@ -90,8 +88,12 @@ class Gemini(AsyncGeneratorProvider):
90 88 if driver:
91 89 driver.close()
92 90
93 if "__Secure-1PSID" not in cookies:
94 raise MissingAuthError('Missing "__Secure-1PSID" cookie')
91 if not snlm0e:
92 if "__Secure-1PSID" not in cookies:
93 raise MissingAuthError('Missing "__Secure-1PSID" cookie')
94 snlm0e = await cls.fetch_snlm0e(cookies, proxy)
95 if not snlm0e:
96 raise RuntimeError("Invalid auth. SNlM0e not found")
95 97
96 98 image_url = await cls.upload_image(to_bytes(image), image_name, proxy) if image else None
97 99
@@ -99,14 +101,6 @@ class Gemini(AsyncGeneratorProvider):
99 101 cookies=cookies,
100 102 headers=REQUEST_HEADERS
101 103 ) as session:
102 async with session.get(cls.url, proxy=proxy) as response:
103 text = await response.text()
104 match = re.search(r'SNlM0e\":\"(.*?)\"', text)
105 if match:
106 snlm0e = match.group(1)
107 else:
108 raise RuntimeError("SNlM0e not found")
109
110 104 params = {
111 105 'bl': REQUEST_BL_PARAM,
112 106 '_reqid': random.randint(1111, 9999),
@@ -204,4 +198,16 @@ class Gemini(AsyncGeneratorProvider):
204 198 upload_url, headers=headers, data=image, proxy=proxy
205 199 ) as response:
206 200 response.raise_for_status()
207 return await response.text()
201 return await response.text()
202
203 @classmethod
204 async def fetch_snlm0e(cls, cookies: Cookies, proxy: str = None):
205 async with ClientSession(
206 cookies=cookies,
207 headers=REQUEST_HEADERS
208 ) as session:
209 async with session.get(cls.url, proxy=proxy) as response:
210 text = await response.text()
211 match = re.search(r'SNlM0e\":\"(.*?)\"', text)
212 if match:
213 return match.group(1)