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

XFEstudio/gpt4free

fix: correct typo in API section title and update links, and adjust provider aliases

- Changed "Inference API" to "Interference API" and updated corresponding documentation links in README.md - Removed "o1" and "dall-e-3" entries from Copilot.py model_aliases - Added "stream" and "extra_body" parameters with default values in Azure.py's create_async_generator method - In CopilotAccount.py, included model_aliases with "gpt-4", "gpt-4o", "o1", and "dall-e-3" - Updated conditional for provider comparison from "==" to "in" list in any_provider.py - Modified g4f/api/__init__.py to set g4f_api_key from environment variable - In backend_api.py, added "user" field to cached data with default "unknown" - Changed logic in OpenaiTemplate.py read_response to check if "choice" exists before processing, and cleaned up indentation and conditionals in response parsing - Removed unnecessary "stop" and "prompt" parameters from comments or unused code in OpenaiTemplate.py - Tightened the check for "provider" comparison in any_provider.py to handle multiple providers properly

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

代码差异

9 个文件 +50 -38
Modified README.md +3 -3
@@ -242,11 +242,11 @@ python -m g4f --port 8080 --debug
242 242
243 243 ---
244 244
245 ### 🤖 Inference API
245 ### 🤖 Interference API
246 246
247 The **Inference API** enables seamless integration with OpenAI's services through G4F, allowing you to deploy efficient AI solutions.
247 The **Interference API** enables seamless integration with OpenAI's services through G4F, allowing you to deploy efficient AI solutions.
248 248
249 - **Documentation**: [Inference API Docs](https://github.com/gpt4free/g4f.dev/blob/main/docs/inference-api.md)
249 - **Documentation**: [Interference API Docs](https://github.com/gpt4free/g4f.dev/blob/main/docs/interference-api.md)
250 250 - **Endpoint**: `http://localhost:1337/v1`
251 251 - **Swagger UI**: Explore the OpenAPI documentation via Swagger UI at `http://localhost:1337/docs`
252 252 - **Provider Selection**: [How to Specify a Provider?](https://github.com/gpt4free/g4f.dev/blob/main/docs/selecting_a_provider.md)
Modified g4f/Provider/Copilot.py +0 -2
@@ -50,8 +50,6 @@ class Copilot(AsyncAuthedProvider, ProviderModelMixin):
50 50 model_aliases = {
51 51 "gpt-4": default_model,
52 52 "gpt-4o": default_model,
53 "o1": "Think Deeper",
54 "dall-e-3": default_model
55 53 }
56 54
57 55 websocket_url = "wss://copilot.microsoft.com/c/api/chat?api-version=2"
Modified g4f/Provider/needs_auth/Azure.py +11 -3
@@ -46,15 +46,14 @@ class Azure(OpenaiTemplate):
46 46 cls,
47 47 model: str,
48 48 messages: Messages,
49 stream: bool = True,
50 extra_body: dict = None,
49 51 api_key: str = None,
50 52 api_endpoint: str = None,
51 53 **kwargs
52 54 ) -> AsyncResult:
53 55 if not model:
54 56 model = os.environ.get("AZURE_DEFAULT_MODEL", cls.default_model)
55 if model in cls.model_extra_body:
56 for key, value in cls.model_extra_body[model].items():
57 kwargs.setdefault(key, value)
58 57 if not api_key:
59 58 raise ValueError(f"API key is required for Azure provider. Ask for API key in the {cls.login_url} Discord server.")
60 59 if not api_endpoint:
@@ -65,12 +64,21 @@ class Azure(OpenaiTemplate):
65 64 raise ModelNotFoundError(f"No API endpoint found for model: {model}")
66 65 if not api_endpoint:
67 66 api_endpoint = os.environ.get("AZURE_API_ENDPOINT")
67 if extra_body is None:
68 if model in cls.model_extra_body:
69 extra_body = cls.model_extra_body[model]
70 else:
71 extra_body = {}
72 if stream:
73 extra_body.setdefault("stream_options", {"include_usage": True})
68 74 try:
69 75 async for chunk in super().create_async_generator(
70 76 model=model,
71 77 messages=messages,
78 stream=stream,
72 79 api_key=api_key,
73 80 api_endpoint=api_endpoint,
81 extra_body=extra_body,
74 82 **kwargs
75 83 ):
76 84 yield chunk
Modified g4f/Provider/needs_auth/CopilotAccount.py +6 -2
@@ -3,10 +3,8 @@ from __future__ import annotations
3 3 import os
4 4 from typing import AsyncIterator
5 5
6 from ..base_provider import AsyncAuthedProvider
7 6 from ..Copilot import Copilot, readHAR, has_nodriver, get_access_token_and_cookies
8 7 from ...providers.response import AuthResult, RequestLogin
9 from ...typing import AsyncResult, Messages
10 8 from ...errors import NoValidHarFileError
11 9 from ... import debug
12 10
@@ -16,6 +14,12 @@ class CopilotAccount(Copilot):
16 14 parent = "Copilot"
17 15 default_model = "Copilot"
18 16 default_vision_model = default_model
17 model_aliases = {
18 "gpt-4": default_model,
19 "gpt-4o": default_model,
20 "o1": "Think Deeper",
21 "dall-e-3": default_model
22 }
19 23
20 24 @classmethod
21 25 async def on_auth_async(cls, proxy: str = None, **kwargs) -> AsyncIterator:
Modified g4f/Provider/template/OpenaiTemplate.py +20 -20
@@ -67,6 +67,7 @@ class OpenaiTemplate(AsyncGeneratorProvider, ProviderModelMixin, RaiseErrorMixin
67 67 stop: Union[str, list[str]] = None,
68 68 stream: bool = None,
69 69 prompt: str = None,
70 user: str = None,
70 71 headers: dict = None,
71 72 impersonate: str = None,
72 73 download_media: bool = True,
@@ -120,6 +121,7 @@ class OpenaiTemplate(AsyncGeneratorProvider, ProviderModelMixin, RaiseErrorMixin
120 121 top_p=top_p,
121 122 stop=stop,
122 123 stream="audio" not in extra_parameters if stream is None else stream,
124 user=user,
123 125 **extra_parameters,
124 126 **extra_body
125 127 )
@@ -185,30 +187,28 @@ async def read_response(response: StreamResponse, stream: bool, prompt: str, pro
185 187 yield ProviderInfo(**provider_info, model=model)
186 188 model_returned = True
187 189 choice = next(iter(data["choices"]), None)
188 if not choice:
189 continue
190 if "content" in choice["delta"] and choice["delta"]["content"]:
191 delta = choice["delta"]["content"]
192 if first:
193 delta = delta.lstrip()
194 if delta:
195 first = False
196 if reasoning:
197 yield Reasoning(status="")
198 reasoning = False
199 yield delta
200 tool_calls = choice.get("delta", {}).get("tool_calls")
201 if tool_calls:
202 yield ToolCalls(choice["delta"]["tool_calls"])
203 reasoning_content = choice.get("delta", {}).get("reasoning_content")
204 if reasoning_content:
205 reasoning = True
206 yield Reasoning(reasoning_content)
190 if choice:
191 if "content" in choice["delta"] and choice["delta"]["content"]:
192 delta = choice["delta"]["content"]
193 if first:
194 delta = delta.lstrip()
195 if delta:
196 first = False
197 if reasoning:
198 yield Reasoning(status="")
199 reasoning = False
200 yield delta
201 tool_calls = choice.get("delta", {}).get("tool_calls")
202 if tool_calls:
203 yield ToolCalls(choice["delta"]["tool_calls"])
204 reasoning_content = choice.get("delta", {}).get("reasoning_content")
205 if reasoning_content:
206 reasoning = True
207 yield Reasoning(reasoning_content)
207 208 if "usage" in data and data["usage"]:
208 209 yield Usage(**data["usage"])
209 210 if choice and choice.get("finish_reason") is not None:
210 211 yield FinishReason(choice["finish_reason"])
211 break
212 212 else:
213 213 await raise_for_status(response)
214 214 async for chunk in save_response_media(response, prompt, [model]):
Modified g4f/api/__init__.py +3 -2
@@ -175,7 +175,7 @@ class ErrorResponse(Response):
175 175
176 176 class AppConfig:
177 177 ignored_providers: Optional[list[str]] = None
178 g4f_api_key: Optional[str] = None
178 g4f_api_key: Optional[str] = os.environ.get("G4F_API_KEY", None)
179 179 ignore_cookie_files: bool = False
180 180 model: str = None
181 181 provider: str = None
@@ -188,7 +188,8 @@ class AppConfig:
188 188 @classmethod
189 189 def set_config(cls, **data):
190 190 for key, value in data.items():
191 setattr(cls, key, value)
191 if value is not None:
192 setattr(cls, key, value)
192 193
193 194 def update_headers(request: Request, user: str) -> Request:
194 195 new_headers = request.headers.mutablecopy()
Modified g4f/gui/server/backend_api.py +2 -1
@@ -213,8 +213,9 @@ class Backend_Api(Api):
213 213 cache_dir = Path(get_cookies_dir()) / ".usage"
214 214 cache_file = cache_dir / f"{datetime.date.today()}.jsonl"
215 215 cache_dir.mkdir(parents=True, exist_ok=True)
216 data = {**request.json, "user": request.headers.get("x-user", "unknown")}
216 217 with cache_file.open("a" if cache_file.exists() else "w") as f:
217 f.write(f"{json.dumps(request.json)}\n")
218 f.write(f"{json.dumps(data)}\n")
218 219 return {}
219 220
220 221 @app.route('/backend-api/v2/usage/<date>', methods=['GET'])
Modified g4f/providers/any_model_map.py +2 -2
@@ -27,7 +27,7 @@ model_map = {
27 27 "Yqcloud": "gpt-4",
28 28 "WeWordle": "gpt-4",
29 29 "OpenaiChat": "gpt-4",
30 "CopilotAccount": "Copilot",
30 "Copilot": "Copilot",
31 31 "HarProvider": [
32 32 "gpt-4-1106-preview",
33 33 "gpt-4-0125-preview",
@@ -52,7 +52,7 @@ model_map = {
52 52 "Blackbox": "gpt-4o",
53 53 "PollinationsAI": "openai",
54 54 "OpenaiChat": "gpt-4o",
55 "CopilotAccount": "Copilot",
55 "Copilot": "Copilot",
56 56 "HarProvider": [
57 57 "chatgpt-4o-latest-20250326",
58 58 "chatgpt-4o-latest-20250129",
Modified g4f/providers/any_provider.py +3 -3
@@ -9,7 +9,7 @@ from ..image import is_data_an_audio
9 9 from ..providers.retry_provider import IterListProvider
10 10 from ..Provider.needs_auth import OpenaiChat, CopilotAccount
11 11 from ..Provider.hf_space import HuggingSpace
12 from ..Provider import Cloudflare, Gemini, GeminiPro, Grok, DeepSeekAPI, PerplexityLabs, LambdaChat, PollinationsAI, PuterJS
12 from ..Provider import Copilot, Cloudflare, Gemini, GeminiPro, Grok, DeepSeekAPI, PerplexityLabs, LambdaChat, PollinationsAI, PuterJS
13 13 from ..Provider import Microsoft_Phi_4_Multimodal, DeepInfraChat, Blackbox, OIVSCodeSer0501, OIVSCodeSer2, TeachAnything, OperaAria, Startnest
14 14 from ..Provider import WeWordle, Yqcloud, Chatai, ImageLabs, LegacyLMArena, LMArenaBeta, Free2GPT
15 15 from ..Provider import EdgeTTS, gTTS, MarkItDown, OpenAIFM
@@ -29,7 +29,7 @@ PROVIERS_LIST_1 = [
29 29 ]
30 30
31 31 PROVIERS_LIST_2 = [
32 OpenaiChat, CopilotAccount, PollinationsAI, PerplexityLabs, Gemini, Grok
32 OpenaiChat, Copilot, CopilotAccount, PollinationsAI, PerplexityLabs, Gemini, Grok
33 33 ]
34 34
35 35 PROVIERS_LIST_3 = [
@@ -129,7 +129,7 @@ class AnyModelProviderMixin(ProviderModelMixin):
129 129 if not provider.working:
130 130 continue
131 131 try:
132 if provider == CopilotAccount:
132 if provider in [Copilot, CopilotAccount]:
133 133 for model in provider.model_aliases.keys():
134 134 if model not in cls.model_map:
135 135 cls.model_map[model] = {}