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

XFEstudio/gpt4free

Fix build docker image

c0e323b5
hlohaus <983577+hlohaus@users.noreply.github.com>
提交于

代码差异

6 个文件 +285 -43
Modified docker/Dockerfile +1 -1
@@ -33,7 +33,7 @@ COPY docker/supervisor-api.conf /etc/supervisor/conf.d/api.conf
33 33 COPY docker/background.png /usr/share/images/fluxbox/ubuntu-light.png
34 34
35 35 # Add user, fix permissions
36 RUN chown "${SEL_UID}:${SEL_GID}" $HOME/.local
36 RUN chown "${SEL_UID}:${SEL_GID}" $HOME/.local /opt/venv/share
37 37
38 38 # Switch user
39 39 USER $SEL_UID
Modified g4f/Provider/needs_auth/Grok.py +36 -28
@@ -3,14 +3,16 @@ from __future__ import annotations
3 3 import os
4 4 import json
5 5 import time
6 import nodriver
7 import asyncio
6 8 from typing import Dict, Any, AsyncIterator
7 9
8 from ...typing import Messages, Cookies, AsyncResult
10 from ...typing import Messages, AsyncResult
9 11 from ...providers.response import JsonConversation, Reasoning, ImagePreview, ImageResponse, TitleGeneration, AuthResult, RequestLogin
10 from ...requests import StreamSession, get_args_from_nodriver, DEFAULT_HEADERS
12 from ...requests import StreamSession, get_nodriver, DEFAULT_HEADERS
11 13 from ...requests.raise_for_status import raise_for_status
12 14 from ..base_provider import AsyncAuthedProvider, ProviderModelMixin
13 from ..helper import format_prompt, get_cookies, get_last_user_message
15 from ..helper import format_prompt, get_last_user_message
14 16
15 17 class Conversation(JsonConversation):
16 18 def __init__(self,
@@ -33,30 +35,40 @@ class Grok(AsyncAuthedProvider, ProviderModelMixin):
33 35 model_aliases = {"grok-3-r1": "grok-3-thinking"}
34 36
35 37 @classmethod
36 async def on_auth_async(cls, cookies: Cookies = None, proxy: str = None, **kwargs) -> AsyncIterator:
37 if cookies is None:
38 cookies = get_cookies(cls.cookie_domain, False, True, False)
39 if cookies is not None and "sso" in cookies:
40 yield AuthResult(
41 cookies=cookies,
42 impersonate="chrome",
43 proxy=proxy,
44 headers=DEFAULT_HEADERS
45 )
46 return
38 async def on_auth_async(cls, proxy: str = None, **kwargs) -> AsyncIterator:
39 auth_result = AuthResult(headers=DEFAULT_HEADERS, impersonate="chrome")
40 auth_result.headers["referer"] = cls.url + "/"
41 browser, stop_browser = await get_nodriver(proxy=proxy)
47 42 yield RequestLogin(cls.__name__, os.environ.get("G4F_LOGIN_URL") or "")
48 yield AuthResult(
49 **await get_args_from_nodriver(
50 cls.url,
51 proxy=proxy,
52 wait_for='[href="/chat#private"]'
53 )
54 )
43 try:
44 page = browser.main_tab
45 has_headers = False
46 def on_request(event: nodriver.cdp.network.RequestWillBeSent, page=None):
47 nonlocal has_headers
48 if event.request.url.startswith(cls.conversation_url + "/new"):
49 for key, value in event.request.headers.items():
50 auth_result.headers[key.lower()] = value
51 has_headers = True
52 await page.send(nodriver.cdp.network.enable())
53 page.add_handler(nodriver.cdp.network.RequestWillBeSent, on_request)
54 page = await browser.get(cls.url)
55 auth_result.headers["user-agent"] = await page.evaluate("window.navigator.userAgent", return_by_value=True)
56 while True:
57 if has_headers:
58 break
59 await asyncio.sleep(1)
60 auth_result.cookies = {}
61 for c in await page.send(nodriver.cdp.network.get_cookies([cls.url])):
62 auth_result.cookies[c.name] = c.value
63 await page.close()
64 finally:
65 stop_browser()
66 yield auth_result
55 67
56 68 @classmethod
57 69 async def _prepare_payload(cls, model: str, message: str) -> Dict[str, Any]:
58 70 return {
59 "temporary": False,
71 "temporary": True,
60 72 "modelName": "grok-latest" if model == "grok-2" else "grok-3",
61 73 "message": message,
62 74 "fileAttachments": [],
@@ -83,7 +95,6 @@ class Grok(AsyncAuthedProvider, ProviderModelMixin):
83 95 model: str,
84 96 messages: Messages,
85 97 auth_result: AuthResult,
86 return_conversation: bool = True,
87 98 conversation: Conversation = None,
88 99 **kwargs
89 100 ) -> AsyncResult:
@@ -99,7 +110,6 @@ class Grok(AsyncAuthedProvider, ProviderModelMixin):
99 110 url = f"{cls.conversation_url}/{conversation_id}/responses"
100 111 async with session.post(url, json=payload) as response:
101 112 await raise_for_status(response)
102
103 113 thinking_duration = None
104 114 async for line in response.iter_lines():
105 115 if line:
@@ -133,9 +143,7 @@ class Grok(AsyncAuthedProvider, ProviderModelMixin):
133 143 title = result.get("title", {}).get("newTitle", "")
134 144 if title:
135 145 yield TitleGeneration(title)
136
137
138 146 except json.JSONDecodeError:
139 147 continue
140 if return_conversation and conversation_id is not None:
141 yield Conversation(conversation_id)
148 # if conversation_id is not None:
149 # yield Conversation(conversation_id)
Modified g4f/client/__init__.py +11 -6
@@ -41,7 +41,7 @@ except NameError:
41 41 def add_chunk(content, chunk):
42 42 if content == "" and isinstance(chunk, (MediaResponse, AudioResponse)):
43 43 content = chunk
44 else:
44 elif not isinstance(chunk, Reasoning):
45 45 content = str(content) + str(chunk)
46 46 return content
47 47
@@ -65,6 +65,7 @@ def iter_response(
65 65 stop: Optional[list[str]] = None
66 66 ) -> ChatCompletionResponseType:
67 67 content = ""
68 reasoning_content = []
68 69 finish_reason = None
69 70 tool_calls = None
70 71 usage = None
@@ -92,9 +93,8 @@ def iter_response(
92 93 elif isinstance(chunk, ProviderInfo):
93 94 provider = chunk
94 95 continue
95 elif isinstance(chunk, BaseConversation):
96 yield chunk
97 continue
96 elif isinstance(chunk, Reasoning):
97 reasoning_content.append(chunk)
98 98 elif isinstance(chunk, HiddenResponse):
99 99 continue
100 100 elif isinstance(chunk, Exception):
@@ -141,7 +141,8 @@ def iter_response(
141 141 chat_completion = ChatCompletion.model_construct(
142 142 content, finish_reason, completion_id, int(time.time()), usage=usage,
143 143 **filter_none(tool_calls=[ToolCallModel.model_construct(**tool_call) for tool_call in tool_calls]) if tool_calls is not None else {},
144 conversation=None if conversation is None else conversation.get_dict()
144 conversation=None if conversation is None else conversation.get_dict(),
145 reasoning_content=reasoning_content if reasoning_content else None
145 146 )
146 147 if provider is not None:
147 148 chat_completion.provider = provider.name
@@ -168,6 +169,7 @@ async def async_iter_response(
168 169 stop: Optional[list[str]] = None
169 170 ) -> AsyncChatCompletionResponseType:
170 171 content = ""
172 reasoning_content = []
171 173 finish_reason = None
172 174 completion_id = ''.join(random.choices(string.ascii_letters + string.digits, k=28))
173 175 idx = 0
@@ -193,6 +195,8 @@ async def async_iter_response(
193 195 elif isinstance(chunk, ProviderInfo):
194 196 provider = chunk
195 197 continue
198 elif isinstance(chunk, Reasoning) and not stream:
199 reasoning_content.append(chunk)
196 200 elif isinstance(chunk, HiddenResponse):
197 201 continue
198 202 elif isinstance(chunk, Exception):
@@ -241,7 +245,8 @@ async def async_iter_response(
241 245 **filter_none(
242 246 tool_calls=[ToolCallModel.model_construct(**tool_call) for tool_call in tool_calls]
243 247 ) if tool_calls is not None else {},
244 conversation=conversation
248 conversation=conversation,
249 reasoning_content=reasoning_content if reasoning_content else None
245 250 )
246 251 if provider is not None:
247 252 chat_completion.provider = provider.name
Modified g4f/client/stubs.py +16 -5
@@ -7,6 +7,7 @@ from time import time
7 7 from ..image import extract_data_uri
8 8 from ..image.copy_images import get_media_dir
9 9 from ..client.helper import filter_markdown
10 from ..providers.response import Reasoning
10 11 from .helper import filter_none
11 12
12 13 try:
@@ -132,16 +133,21 @@ class ResponseMessageContent(BaseModel):
132 133 class ChatCompletionMessage(BaseModel):
133 134 role: str
134 135 content: str
136 reasoning_content: list[Reasoning] = None
135 137 tool_calls: list[ToolCallModel] = None
136 138
137 139 @classmethod
138 def model_construct(cls, content: str, tool_calls: list = None):
139 return super().model_construct(role="assistant", content=content, **filter_none(tool_calls=tool_calls))
140 def model_construct(cls, content: str, reasoning_content: list[Reasoning] = None, tool_calls: list = None):
141 return super().model_construct(role="assistant", content=content, **filter_none(tool_calls=tool_calls, reasoning_content=reasoning_content))
140 142
141 143 @field_serializer('content')
142 144 def serialize_content(self, content: str):
143 145 return str(content)
144 146
147 @field_serializer('reasoning_content')
148 def serialize_reasoning_content(self, reasoning_content: list):
149 return "".join([str(content) for content in reasoning_content]) if reasoning_content else None
150
145 151 def save(self, filepath: str, allowed_types = None):
146 152 if hasattr(self.content, "data"):
147 153 os.rename(self.content.data.replace("/media", get_media_dir()), filepath)
@@ -184,7 +190,8 @@ class ChatCompletion(BaseModel):
184 190 created: int = None,
185 191 tool_calls: list[ToolCallModel] = None,
186 192 usage: UsageModel = None,
187 conversation: dict = None
193 conversation: dict = None,
194 reasoning_content: list[Reasoning] = None
188 195 ):
189 196 return super().model_construct(
190 197 id=f"chatcmpl-{completion_id}" if completion_id else None,
@@ -193,7 +200,7 @@ class ChatCompletion(BaseModel):
193 200 model=None,
194 201 provider=None,
195 202 choices=[ChatCompletionChoice.model_construct(
196 ChatCompletionMessage.model_construct(content, tool_calls),
203 ChatCompletionMessage.model_construct(content, reasoning_content, tool_calls),
197 204 finish_reason,
198 205 )],
199 206 **filter_none(usage=usage, conversation=conversation)
@@ -245,16 +252,20 @@ class ClientResponse(BaseModel):
245 252 class ChatCompletionDelta(BaseModel):
246 253 role: str
247 254 content: Optional[str]
255 reasoning_content: Optional[str] = None
248 256
249 257 @classmethod
250 258 def model_construct(cls, content: Optional[str]):
259 if isinstance(content, Reasoning):
260 return super().model_construct(role="reasoning", content=content, reasoning_content=str(content))
251 261 return super().model_construct(role="assistant", content=content)
252 262
253 263 @field_serializer('content')
254 264 def serialize_content(self, content: Optional[str]):
255 265 if content is None:
256 266 return ""
257
267 if isinstance(content, Reasoning):
268 return None
258 269 return str(content)
259 270
260 271 class ChatCompletionDeltaChoice(BaseModel):
Modified g4f/tools/files.py +6 -3
@@ -89,11 +89,14 @@ def secure_filename(filename: str) -> str:
89 89 # Keep letters, numbers, basic punctuation and all Unicode chars
90 90 filename = re.sub(
91 91 r'[^\w.,_+-]+',
92 '_',
93 unquote(filename).strip(),
92 '_',
93 unquote(filename).strip(),
94 94 flags=re.UNICODE
95 95 )
96 filename = filename[:100].strip(".,_-+")
96 max_length = 100
97 if len(filename.encode()) > len(filename):
98 max_length = 50
99 filename = filename[:max_length].strip(".,_+-")
97 100 return filename
98 101
99 102 def supports_filename(filename: str):
Added new.py +215 -0
@@ -0,0 +1,215 @@
1 import json
2 import uuid
3 import g4f.debug
4 import requests
5 from g4f.client import Client
6
7 def upload_and_process(files_or_urls, bucket_id=None):
8 if bucket_id is None:
9 bucket_id = str(uuid.uuid4())
10
11 if isinstance(files_or_urls, list): # URLs
12 files = {'files': ('downloads.json', json.dumps(
13 files_or_urls), 'application/json')}
14 elif isinstance(files_or_urls, dict): # Files
15 files = files_or_urls
16 else:
17 raise ValueError(
18 "files_or_urls must be a list of URLs or a dictionary of files")
19
20 upload_response = requests.post(
21 f'http://localhost:8080/backend-api/v2/files/{bucket_id}', files=files)
22
23 if upload_response.status_code == 200:
24 upload_data = upload_response.json()
25 print(f"Upload successful. Bucket ID: {upload_data['bucket_id']}")
26 else:
27 print(
28 f"Upload failed: {upload_response.status_code} - {upload_response.text}")
29
30 response = requests.get(
31 f'http://localhost:8080/backend-api/v2/files/{bucket_id}', stream=True, headers={'Accept': 'text/event-stream'})
32 for line in response.iter_lines():
33 if line:
34 line = line.decode('utf-8')
35 if line.startswith('data:'):
36 try:
37 data = json.loads(line[5:]) # remove data: prefix
38 if "action" in data:
39 print(f"SSE Event: {data}")
40 elif "error" in data:
41 print(f"Error: {data['error']['message']}")
42 else:
43 # Assuming it's file content
44 print(f"File data received: {data}")
45 except json.JSONDecodeError as e:
46 print(f"Error decoding JSON: {e}")
47 else:
48 print(f"Unhandled SSE event: {line}")
49 response.close()
50 return bucket_id
51
52
53 # Example with URLs
54
55 # Enable debug mode
56 g4f.debug.logging = True
57
58 client = Client()
59
60 # Upload example file
61 files = {'files': ('demo.docx', open('demo.docx', 'rb'))}
62 bucket_id = upload_and_process(files)
63
64 # Send request with file:
65 response = client.chat.completions.create(
66 model='gpt-4o',
67 messages=[{"role": "user", "content": [
68 {"type": "text", "text": "Discribe this file."},
69 {"bucket_id": bucket_id}
70 ]}],
71 )
72 print(response.choices[0].message.content)
73 exit()
74 # import asyncio
75 # from g4f.client import AsyncClient
76 # import g4f.Provider
77
78 # async def main():
79 # client = AsyncClient(provider=g4f.Provider.MarkItDown)
80
81 # # Transcribe a audio file
82 # with open("audio.wav", "rb") as audio_file:
83 # response = await client.chat.completions.create("", media=[audio_file])
84 # print(response.choices[0].message.content)
85
86 # if __name__ == "__main__":
87 # asyncio.run(main())
88
89 #exit()
90 import requests
91
92 # Open the audio file in binary mode
93 with open('demo.docx', 'rb') as audio_file:
94 # Make the POST request
95 response = requests.post('http://localhost:8080/api/markitdown', files={'file': audio_file})
96
97 # Check the response and print the transcription
98 if response.status_code == 200:
99 data = response.json()
100 print(data['text'])
101 else:
102 print(f"Error: {response.status_code}, {response.text}")
103 exit()
104
105 # from openai import OpenAI
106 # client = OpenAI(base_url="http://localhost:8080/v1", api_key="secret")
107
108 # with open("audio.wav", "rb") as file:
109 # transcript = client.audio.transcriptions.create(
110 # model="",
111 # extra_body={"provider": "MarkItDown"},
112 # file=file
113 # )
114 # print(transcript.text)
115
116 exit()
117 import asyncio
118 import time
119 from g4f import AsyncClient
120 from g4f.Provider import PollinationsAI
121 async def test():
122 client = AsyncClient()
123 response = client.chat.completions.create("guten tag", stream=True, provider=HarProvider)
124 async for chunk in response:
125 if chunk.choices[0].finish_reason == "stop":
126 break
127 print(chunk.choices[0].delta.content, end="", flush=True)
128 print()
129
130 asyncio.run(test())
131 time.sleep(1)
132 exit()
133
134 client = Client(provider=PollinationsAI)
135 response = client.media.generate("Hello", model="hypnosis-tracy")
136 response.data[0].save("hypnosis.mp3")
137
138 client = Client(provider=Gemini)
139 response = client.media.generate("Hello", model="gemini-audio")
140 response.data[0].save("gemini.ogx")
141
142 client = Client(provider=EdgeTTS)
143 response = client.media.generate("Hello", audio={"locale": "en-US"})
144 response.data[0].save("edge-tts.mp3")
145
146 exit()
147 import requests
148 import uuid
149 import json
150
151 def upload_and_process(files_or_urls, bucket_id=None):
152 if bucket_id is None:
153 bucket_id = str(uuid.uuid4())
154
155 if isinstance(files_or_urls, list): #URLs
156 files = {'files': ('downloads.json', json.dumps(files_or_urls), 'application/json')}
157 elif isinstance(files_or_urls, dict): #Files
158 files = files_or_urls
159 else:
160 raise ValueError("files_or_urls must be a list of URLs or a dictionary of files")
161
162 upload_response = requests.post(f'http://localhost:8080/v1/files/{bucket_id}', files=files)
163
164 if upload_response.status_code == 200:
165 upload_data = upload_response.json()
166 print(f"Upload successful. Bucket ID: {upload_data['bucket_id']}")
167 else:
168 print(f"Upload failed: {upload_response.status_code} - {upload_response.text}")
169
170 response = requests.get(f'http://localhost:8080/v1/files/{bucket_id}', stream=True, headers={'Accept': 'text/event-stream'})
171 for line in response.iter_lines():
172 if line:
173 line = line.decode('utf-8')
174 if line.startswith('data:'):
175 try:
176 data = json.loads(line[5:]) #remove data: prefix
177 if "action" in data:
178 print(f"SSE Event: {data}")
179 elif "error" in data:
180 print(f"Error: {data['error']['message']}")
181 else:
182 print(f"File data received: {data}") #Assuming it's file content
183 except json.JSONDecodeError as e:
184 print(f"Error decoding JSON: {e}")
185 else:
186 print(f"Unhandled SSE event: {line}")
187 response.close()
188 return bucket_id
189
190 # Example with URLs
191 #Example with files
192 #files = {'files': open('document.pdf', 'rb'), 'files': open('data.json', 'rb')}
193 #bucket_id = upload_and_process(files)
194 import asyncio
195 from g4f.client import Client
196
197 import g4f.debug
198 g4f.debug.logging = True
199
200 client = Client()
201
202
203 files = {'files': ('demo.docx', open('demo.docx', 'rb'))}
204 bucket_id = upload_and_process(files)
205
206
207 response = client.chat.completions.create(
208 [{"role": "user", "content": [
209 {"type": "text", "text": "Discribe this file."},
210 {"bucket_id": bucket_id}
211 ]}],
212 "o1",
213 )
214 print(response.choices[0].message.content)
215