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

XFEstudio/gpt4free

Support "Think Deeper" in Copilot Improve Documentation

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

代码差异

14 个文件 +189 -82
Modified README.md +20 -19
@@ -97,31 +97,31 @@ Is your site on this repository and you want to take it down? Send an email to t
97 97 1. **Install Docker:** [Download and install Docker](https://docs.docker.com/get-docker/).
98 98 2. **Set Up Directories:** Before running the container, make sure the necessary data directories exist or can be created. For example, you can create and set ownership on these directories by running:
99 99 ```bash
100 mkdir -p ${PWD}/har_and_cookies ${PWD}/generated_images
101 sudo chown -R 1200:1201 ${PWD}/har_and_cookies ${PWD}/generated_images
100 mkdir -p ${PWD}/har_and_cookies ${PWD}/generated_images
101 sudo chown -R 1200:1201 ${PWD}/har_and_cookies ${PWD}/generated_images
102 102 ```
103 103 3. **Run the Docker Container:** Use the following commands to pull the latest image and start the container (Only x64):
104 104 ```bash
105 docker pull hlohaus789/g4f
106 docker run -p 8080:8080 -p 7900:7900 \
107 --shm-size="2g" \
108 -v ${PWD}/har_and_cookies:/app/har_and_cookies \
109 -v ${PWD}/generated_images:/app/generated_images \
110 hlohaus789/g4f:latest
105 docker pull hlohaus789/g4f
106 docker run -p 8080:8080 -p 7900:7900 \
107 --shm-size="2g" \
108 -v ${PWD}/har_and_cookies:/app/har_and_cookies \
109 -v ${PWD}/generated_images:/app/generated_images \
110 hlohaus789/g4f:latest
111 111 ```
112 112
113 113 4. **Running the Slim Docker Image:** And use the following commands to run the Slim Docker image. This command also updates the `g4f` package at startup and installs any additional dependencies: (x64 and arm64)
114 114 ```bash
115 mkdir -p ${PWD}/har_and_cookies ${PWD}/generated_images
116 chown -R 1000:1000 ${PWD}/har_and_cookies ${PWD}/generated_images
117 docker run \
118 -p 1337:1337 \
119 -v ${PWD}/har_and_cookies:/app/har_and_cookies \
120 -v ${PWD}/generated_images:/app/generated_images \
121 hlohaus789/g4f:latest-slim \
122 rm -r -f /app/g4f/ \
123 && pip install -U g4f[slim] \
124 && python -m g4f --debug
115 mkdir -p ${PWD}/har_and_cookies ${PWD}/generated_images
116 chown -R 1000:1000 ${PWD}/har_and_cookies ${PWD}/generated_images
117 docker run \
118 -p 1337:1337 \
119 -v ${PWD}/har_and_cookies:/app/har_and_cookies \
120 -v ${PWD}/generated_images:/app/generated_images \
121 hlohaus789/g4f:latest-slim \
122 rm -r -f /app/g4f/ \
123 && pip install -U g4f[slim] \
124 && python -m g4f --debug
125 125 ```
126 126
127 127 5. **Access the Client Interface:**
@@ -248,7 +248,8 @@ Run the Web UI on your smartphone for easy access on the go. Check out the dedic
248 248 - **File API from G4F:** [/docs/file](docs/file.md)
249 249 - **PydanticAI and LangChain Integration for G4F:** [/docs/pydantic_ai](docs/pydantic_ai.md)
250 250 - **Legacy API with python modules:** [/docs/legacy](docs/legacy.md)
251
251 - **G4F - Media Documentation** [/docs/media](/docs/meda.md) *(New)*
252
252 253 ---
253 254
254 255 ## 🔗 Powered by gpt4free
Modified docs/authentication.md +8 -2
@@ -126,7 +126,7 @@ providers = {
126 126 }
127 127
128 128 for provider_name, api_key in providers.items():
129 client = Client(provider=f"g4f.Provider.{provider_name}", api_key=api_key)
129 client = Client(provider=provider_name, api_key=api_key)
130 130 response = client.chat.completions.create(
131 131 model="claude-3.5-sonnet",
132 132 messages=[{"role": "user", "content": f"Hello from {provider_name}!"}]
@@ -144,16 +144,22 @@ for provider_name, api_key in providers.items():
144 144 - Firefox: **Storage** → **Cookies**
145 145
146 146 ```python
147 from g4f.client import Client
147 148 from g4f.Provider import Gemini
148 149
149 # Initialize with cookies
150 # Using with cookies
150 151 client = Client(
151 152 provider=Gemini,
153 )
154 response = client.chat.completions.create(
155 model="", # Default model
156 messages="Hello Google",
152 157 cookies={
153 158 "__Secure-1PSID": "your_cookie_value_here",
154 159 "__Secure-1PSIDTS": "timestamp_value_here"
155 160 }
156 161 )
162 print(f"Gemini: {response.choices[0].message.content}")
157 163 ```
158 164
159 165 ---
Modified docs/gui.md +3 -3
@@ -69,9 +69,9 @@ The G4F GUI is a self-contained, user-friendly interface designed for interactin
69 69 - **Basic Authentication**
70 70 You can set a password for Basic Authentication using the `--g4f-api-key` argument when starting the web server.
71 71
72 ### 9. **Continue Button (ChatGPT & HuggingChat)**
72 ### 9. **Continue Button**
73 73 - **Automatic Detection of Truncated Responses**
74 When using **ChatGPT** or **HuggingChat** providers, responses may occasionally be cut off or truncated.
74 When using providers, responses may occasionally be cut off or truncated.
75 75 - **Continue Button**
76 76 If the GUI detects that the response ended abruptly, a **Continue** button appears directly below the truncated message. Clicking this button sends a follow-up request to the same provider and model, retrieving the rest of the message.
77 77 - **Seamless Conversation Flow**
@@ -154,7 +154,7 @@ http://localhost:8080/chat/
154 154 - **Text/Code:** The generated response appears in the conversation window.
155 155 - **Images:** Generated images are displayed as thumbnails. Click on any thumbnail to view it in full size within the lightbox.
156 156
157 5. **Continue Button (ChatGPT & HuggingChat)**
157 5. **Continue Button**
158 158 - If a response is truncated, a **Continue** button will appear under the last message. Clicking it asks the same provider to continue the response from where it ended.
159 159
160 160 6. **Manage Conversations**
Modified docs/media.md +2 -2
@@ -175,7 +175,7 @@ from g4f.Provider import HuggingFaceMedia
175 175 async def main():
176 176 client = AsyncClient(
177 177 provider=HuggingFaceMedia,
178 api_key="hf_***" # Your API key here
178 api_key=os.getenv("HF_TOKEN") # Your API key here
179 179 )
180 180
181 181 video_models = client.models.get_video()
@@ -214,7 +214,7 @@ from g4f.Provider import HuggingFaceMedia
214 214 async def main():
215 215 client = AsyncClient(
216 216 provider=HuggingFaceMedia,
217 api_key=os.getenv("HUGGINGFACE_API_KEY") # Your API key here
217 api_key=os.getenv("HF_TOKEN") # Your API key here
218 218 )
219 219
220 220 video_models = client.models.get_video()
Modified g4f/Provider/Cloudflare.py +2 -2
@@ -83,9 +83,9 @@ class Cloudflare(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
83 83 pass
84 84 data = {
85 85 "messages": [{
86 "role":"user",
86 **message,
87 87 "content": message["content"] if isinstance(message["content"], str) else "",
88 "parts": [{"type":"text", "text":message["content"]}] if isinstance(message["content"], str) else message["content"]} for message in messages],
88 "parts": [{"type":"text", "text":message["content"]}] if isinstance(message["content"], str) else message} for message in messages],
89 89 "lora": None,
90 90 "model": model,
91 91 "max_tokens": max_tokens,
Modified g4f/Provider/Copilot.py +14 -6
@@ -24,7 +24,7 @@ from .openai.har_file import get_headers, get_har_files
24 24 from ..typing import CreateResult, Messages, MediaListType
25 25 from ..errors import MissingRequirementsError, NoValidHarFileError, MissingAuthError
26 26 from ..requests.raise_for_status import raise_for_status
27 from ..providers.response import BaseConversation, JsonConversation, RequestLogin, ImageResponse
27 from ..providers.response import BaseConversation, JsonConversation, RequestLogin, ImageResponse, FinishReason, SuggestedFollowups
28 28 from ..providers.asyncio import get_running_loop
29 29 from ..tools.media import merge_media
30 30 from ..requests import get_nodriver
@@ -46,10 +46,13 @@ class Copilot(AbstractProvider, ProviderModelMixin):
46 46 supports_stream = True
47 47
48 48 default_model = "Copilot"
49 models = [default_model]
49 models = [default_model, "Think Deeper"]
50 50 model_aliases = {
51 51 "gpt-4": default_model,
52 "o1": default_model,
52 "gpt-4o": default_model,
53 "o1": "Think Deeper",
54 "reasoning": "Think Deeper",
55 "dall-e-3": default_model
53 56 }
54 57
55 58 websocket_url = "wss://copilot.microsoft.com/c/api/chat?api-version=2"
@@ -75,10 +78,10 @@ class Copilot(AbstractProvider, ProviderModelMixin):
75 78 ) -> CreateResult:
76 79 if not has_curl_cffi:
77 80 raise MissingRequirementsError('Install or update "curl_cffi" package | pip install -U curl_cffi')
78
81 model = cls.get_model(model)
79 82 websocket_url = cls.websocket_url
80 83 headers = None
81 if cls.needs_auth or media is not None:
84 if cls._access_token:
82 85 if api_key is not None:
83 86 cls._access_token = api_key
84 87 if cls._access_token is None:
@@ -163,6 +166,7 @@ class Copilot(AbstractProvider, ProviderModelMixin):
163 166 # "token": clarity_token,
164 167 # "method":"clarity"
165 168 # }).encode(), CurlWsFlag.TEXT)
169 wss.send(json.dumps({"event":"setOptions","supportedCards":["weather","local","image","sports","video","ads","finance"],"ads":{"supportedTypes":["multimedia","product","tourActivity","propertyPromotion","text"]}}));
166 170 wss.send(json.dumps({
167 171 "event": "send",
168 172 "conversationId": conversation_id,
@@ -170,7 +174,7 @@ class Copilot(AbstractProvider, ProviderModelMixin):
170 174 "type": "text",
171 175 "text": prompt,
172 176 }],
173 "mode": "chat"
177 "mode": "reasoning" if "Think" in model else "chat",
174 178 }).encode(), CurlWsFlag.TEXT)
175 179
176 180 is_started = False
@@ -193,6 +197,10 @@ class Copilot(AbstractProvider, ProviderModelMixin):
193 197 elif msg.get("event") == "imageGenerated":
194 198 yield ImageResponse(msg.get("url"), image_prompt, {"preview": msg.get("thumbnailUrl")})
195 199 elif msg.get("event") == "done":
200 yield FinishReason("stop")
201 break
202 elif msg.get("event") == "suggestedFollowups":
203 yield SuggestedFollowups(msg.get("suggestions"))
196 204 break
197 205 elif msg.get("event") == "replaceText":
198 206 yield msg.get("text")
Added g4f/Provider/DuckDuckGo.py +85 -0
@@ -0,0 +1,85 @@
1 from __future__ import annotations
2
3 import asyncio
4
5 try:
6 from duckduckgo_search import DDGS
7 from duckduckgo_search.exceptions import DuckDuckGoSearchException, RatelimitException, ConversationLimitException
8 has_requirements = True
9 except ImportError:
10 has_requirements = False
11 try:
12 import nodriver
13 has_nodriver = True
14 except ImportError:
15 has_nodriver = False
16
17 from ..typing import AsyncResult, Messages
18 from ..requests import get_nodriver
19 from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
20 from .helper import get_last_user_message
21
22 class DuckDuckGo(AsyncGeneratorProvider, ProviderModelMixin):
23 label = "Duck.ai (duckduckgo_search)"
24 url = "https://duckduckgo.com/aichat"
25 api_base = "https://duckduckgo.com/duckchat/v1/"
26
27 working = False
28 supports_stream = True
29 supports_system_message = True
30 supports_message_history = True
31
32 default_model = "gpt-4o-mini"
33 models = [default_model, "meta-llama/Llama-3.3-70B-Instruct-Turbo", "claude-3-haiku-20240307", "o3-mini", "mistralai/Mistral-Small-24B-Instruct-2501"]
34
35 ddgs: DDGS = None
36
37 model_aliases = {
38 "gpt-4": "gpt-4o-mini",
39 "llama-3.3-70b": "meta-llama/Llama-3.3-70B-Instruct-Turbo",
40 "claude-3-haiku": "claude-3-haiku-20240307",
41 "mixtral-small-24b": "mistralai/Mistral-Small-24B-Instruct-2501",
42 }
43
44 @classmethod
45 async def create_async_generator(
46 cls,
47 model: str,
48 messages: Messages,
49 proxy: str = None,
50 timeout: int = 60,
51 **kwargs
52 ) -> AsyncResult:
53 if not has_requirements:
54 raise ImportError("duckduckgo_search is not installed. Install it with `pip install duckduckgo-search`.")
55 if cls.ddgs is None:
56 cls.ddgs = DDGS(proxy=proxy, timeout=timeout)
57 if has_nodriver:
58 await cls.nodriver_auth(proxy=proxy)
59 model = cls.get_model(model)
60 for chunk in cls.ddgs.chat_yield(get_last_user_message(messages), model, timeout):
61 yield chunk
62
63 @classmethod
64 async def nodriver_auth(cls, proxy: str = None):
65 browser, stop_browser = await get_nodriver(proxy=proxy)
66 try:
67 page = browser.main_tab
68 def on_request(event: nodriver.cdp.network.RequestWillBeSent, page=None):
69 if cls.api_base in event.request.url:
70 if "X-Vqd-4" in event.request.headers:
71 cls.ddgs._chat_vqd = event.request.headers["X-Vqd-4"]
72 if "X-Vqd-Hash-1" in event.request.headers:
73 cls.ddgs._chat_vqd_hash = event.request.headers["X-Vqd-Hash-1"]
74 if "F-Fe-Version" in event.request.headers:
75 cls.ddgs._chat_xfe = event.request.headers["F-Fe-Version" ]
76 await page.send(nodriver.cdp.network.enable())
77 page.add_handler(nodriver.cdp.network.RequestWillBeSent, on_request)
78 page = await browser.get(cls.url)
79 while True:
80 if cls.ddgs._chat_vqd:
81 break
82 await asyncio.sleep(1)
83 await page.close()
84 finally:
85 stop_browser()
Modified g4f/Provider/__init__.py +1 -0
@@ -40,6 +40,7 @@ try:
40 40 from .Copilot import Copilot
41 41 from .DDG import DDG
42 42 from .DeepInfraChat import DeepInfraChat
43 from .DuckDuckGo import DuckDuckGo
43 44 from .Dynaspark import Dynaspark
44 45 except ImportError as e:
45 46 debug.error("Providers not loaded (A-D):", e)
Modified g4f/Provider/needs_auth/CopilotAccount.py +0 -5
@@ -19,11 +19,6 @@ class CopilotAccount(AsyncAuthedProvider, Copilot):
19 19 parent = "Copilot"
20 20 default_model = "Copilot"
21 21 default_vision_model = default_model
22 models = [default_model]
23 image_models = models
24 model_aliases = {
25 "dall-e-3": default_model
26 }
27 22
28 23 @classmethod
29 24 async def on_auth_async(cls, proxy: str = None, **kwargs) -> AsyncIterator:
Modified g4f/api/stubs.py +1 -0
@@ -68,6 +68,7 @@ class ImageGenerationConfig(BaseModel):
68 68 aspect_ratio: Optional[str] = None
69 69 n: Optional[int] = None
70 70 negative_prompt: Optional[str] = None
71 resolution: Optional[str] = None
71 72
72 73 class ProviderResponseModel(BaseModel):
73 74 id: str
Modified g4f/gui/client/static/js/chat.v1.js +7 -2
@@ -1325,7 +1325,12 @@ const delete_conversation = async (conversation_id) => {
1325 1325 }
1326 1326 }
1327 1327 }
1328
1328 if (window.share_id && conversation_id == window.start_id) {
1329 const url = `${window.share_url}/backend-api/v2/files/${window.share_id}`;
1330 await fetch(url, {
1331 method: 'DELETE'
1332 });
1333 }
1329 1334 appStorage.removeItem(`conversation:${conversation_id}`);
1330 1335 const item = document.getElementById(`convo-${conversation_id}`);
1331 1336 item.remove();
@@ -2622,7 +2627,7 @@ function connectToSSE(url, do_refine, bucket_id) {
2622 2627 } else if (data.action == "media") {
2623 2628 inputCount.innerText = `File: ${data.filename}`;
2624 2629 const url = `/files/${bucket_id}/media/${data.filename}`;
2625 const media = [{bucket_id: bucket_id, url: url}];
2630 const media = [{bucket_id: bucket_id, url: url, name: data.filename}];
2626 2631 await handle_ask(false, media);
2627 2632 } else if (data.action == "load") {
2628 2633 inputCount.innerText = `Read data: ${formatFileSize(data.size)}`;
Modified g4f/image/__init__.py +1 -1
@@ -37,7 +37,7 @@ EXTENSIONS_MAP: dict[str, str] = {
37 37 "flac": "audio/flac",
38 38 "opus": "audio/opus",
39 39 "ogg": "audio/ogg",
40 "m4a": "audio/mp4",
40 "m4a": "audio/m4a",
41 41 # Video
42 42 "mkv": "video/x-matroska",
43 43 "webm": "video/webm",
Modified g4f/providers/response.py +4 -0
Modified g4f/tools/web_search.py +41 -40