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

XFEstudio/gpt4free

Improve code with ai

dfdb7596
Heiner Lohaus <heiner@lohaus.eu>
提交于

代码差异

3 个文件 +37 -24
Renamed etc/tool/improve_code.py +5 -2
@@ -22,7 +22,10 @@ Improve the code in this file:
22 22 ```py
23 23 {code}
24 24 ```
25 Don't remove anything. Add type hints if possible.
25 Don't remove anything.
26 Add typehints if possible.
27 Don't add any typehints to kwargs.
28 Don't remove license comments.
26 29 """
27 30
28 31 print("Create code...")
@@ -30,7 +33,7 @@ response = []
30 33 for chunk in g4f.ChatCompletion.create(
31 34 model=g4f.models.gpt_35_long,
32 35 messages=[{"role": "user", "content": prompt}],
33 timeout=0,
36 timeout=300,
34 37 stream=True
35 38 ):
36 39 response.append(chunk)
Modified g4f/Provider/helper.py +16 -9
@@ -1,8 +1,10 @@
1 1 from __future__ import annotations
2 2
3 import asyncio, sys
3 import asyncio
4 import sys
4 5 from asyncio import AbstractEventLoop
5 6 from os import path
7 from typing import Dict, List
6 8 import browser_cookie3
7 9
8 10 # Change event loop policy on windows
@@ -13,7 +15,7 @@ if sys.platform == 'win32':
13 15 asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
14 16
15 17 # Local Cookie Storage
16 _cookies: dict[str, dict[str, str]] = {}
18 _cookies: Dict[str, Dict[str, str]] = {}
17 19
18 20 # If event loop is already running, handle nested event loops
19 21 # If "nest_asyncio" is installed, patch the event loop.
@@ -34,11 +36,13 @@ def get_event_loop() -> AbstractEventLoop:
34 36 return event_loop
35 37 except ImportError:
36 38 raise RuntimeError(
37 'Use "create_async" instead of "create" function in a running event loop. Or install the "nest_asyncio" package.')
39 'Use "create_async" instead of "create" function in a running event loop. Or install the "nest_asyncio" package.'
40 )
41
38 42
39 # Load cookies for a domain from all supported browser.
40 # Cache the results in the "_cookies" variable
41 def get_cookies(cookie_domain: str) -> dict:
43 # Load cookies for a domain from all supported browsers.
44 # Cache the results in the "_cookies" variable.
45 def get_cookies(cookie_domain: str) -> Dict[str, str]:
42 46 if cookie_domain not in _cookies:
43 47 _cookies[cookie_domain] = {}
44 48 try:
@@ -49,15 +53,18 @@ def get_cookies(cookie_domain: str) -> dict:
49 53 return _cookies[cookie_domain]
50 54
51 55
52 def format_prompt(messages: list[dict[str, str]], add_special_tokens=False):
56 def format_prompt(messages: List[Dict[str, str]], add_special_tokens=False) -> str:
53 57 if add_special_tokens or len(messages) > 1:
54 58 formatted = "\n".join(
55 ["%s: %s" % ((message["role"]).capitalize(), message["content"]) for message in messages]
59 [
60 "%s: %s" % ((message["role"]).capitalize(), message["content"])
61 for message in messages
62 ]
56 63 )
57 64 return f"{formatted}\nAssistant:"
58 65 else:
59 66 return messages[0]["content"]
60
67
61 68
62 69 def get_browser(user_data_dir: str = None):
63 70 from undetected_chromedriver import Chrome
Modified g4f/requests.py +16 -13
@@ -5,7 +5,7 @@ import json
5 5 import asyncio
6 6 from functools import partialmethod
7 7 from asyncio import Future, Queue
8 from typing import AsyncGenerator
8 from typing import AsyncGenerator, Union, Optional
9 9
10 10 from curl_cffi.requests import AsyncSession, Response
11 11 import curl_cffi
@@ -37,7 +37,14 @@ class StreamResponse:
37 37 async def json(self, **kwargs) -> dict:
38 38 return json.loads(await self.read(), **kwargs)
39 39
40 async def iter_lines(self, chunk_size=None, decode_unicode=False, delimiter=None) -> AsyncGenerator[bytes, None]:
40 async def iter_lines(
41 self, chunk_size: Optional[int] = None, decode_unicode: bool = False, delimiter: Optional[str] = None
42 ) -> AsyncGenerator[bytes, None]:
43 """
44 Copied from: https://requests.readthedocs.io/en/latest/_modules/requests/models/
45 which is under the License: Apache 2.0
46 """
47
41 48 pending: bytes = None
42 49
43 50 async for chunk in self.iter_content(
@@ -60,7 +67,9 @@ class StreamResponse:
60 67 if pending is not None:
61 68 yield pending
62 69
63 async def iter_content(self, chunk_size=None, decode_unicode=False) -> AsyncGenerator[bytes, None]:
70 async def iter_content(
71 self, chunk_size: Optional[int] = None, decode_unicode: bool = False
72 ) -> AsyncGenerator[bytes, None]:
64 73 if chunk_size:
65 74 warnings.warn("chunk_size is ignored, there is no way to tell curl that.")
66 75 if decode_unicode:
@@ -76,14 +85,14 @@ class StreamResponse:
76 85
77 86
78 87 class StreamRequest:
79 def __init__(self, session: AsyncSession, method: str, url: str, **kwargs) -> None:
88 def __init__(self, session: AsyncSession, method: str, url: str, **kwargs: Union[bool, int, str]) -> None:
80 89 self.session: AsyncSession = session
81 90 self.loop: asyncio.AbstractEventLoop = session.loop if session.loop else asyncio.get_running_loop()
82 91 self.queue: Queue[bytes] = Queue()
83 92 self.method: str = method
84 93 self.url: str = url
85 94 self.options: dict = kwargs
86 self.handle: curl_cffi.AsyncCurl = None
95 self.handle: Optional[curl_cffi.AsyncCurl] = None
87 96
88 97 def _on_content(self, data: bytes) -> None:
89 98 if not self.enter.done():
@@ -134,10 +143,7 @@ class StreamRequest:
134 143 response.request = request
135 144 else:
136 145 response = self.session._parse_response(self.curl, request, _, header_buffer)
137 return StreamResponse(
138 response,
139 self.queue
140 )
146 return StreamResponse(response, self.queue)
141 147
142 148 async def __aenter__(self) -> StreamResponse:
143 149 return await self.fetch()
@@ -163,10 +169,7 @@ class StreamRequest:
163 169
164 170 class StreamSession(AsyncSession):
165 171 def request(
166 self,
167 method: str,
168 url: str,
169 **kwargs
172 self, method: str, url: str, **kwargs
170 173 ) -> StreamRequest:
171 174 return StreamRequest(self, method, url, **kwargs)
172 175