返回提交历史
Modified
g4f/api/__init__.py
+9
-7
XFEstudio/gpt4free
refactor(g4f/api/__init__.py): use asynchronous methods in Client
c6d11e5c
代码差异
1 个文件
+9
-7
@@ -17,7 +17,7 @@ from typing import Union, Optional
17
17
18
18
import g4f
19
19
import g4f.debug
20
from g4f.client import AsyncClient
20
from g4f.client import Client
21
21
from g4f.typing import Messages
22
22
from g4f.cookies import read_cookie_files
23
23
@@ -69,7 +69,7 @@ class AppConfig():
69
69
class Api:
70
70
def __init__(self, app: FastAPI) -> None:
71
71
self.app = app
72
self.client = AsyncClient()
72
self.client = Client()
73
73
self.get_g4f_api_key = APIKeyHeader(name="g4f-api-key")
74
74
75
75
def register_authorization(self):
@@ -156,7 +156,8 @@ class Api:
156
156
auth_header = auth_header.split(None, 1)[-1]
157
157
if auth_header and auth_header != "Bearer":
158
158
config.api_key = auth_header
159
response = self.client.chat.completions.create(
159
# Use the asynchronous create method and await it
160
response = await self.client.chat.completions.async_create(
160
161
**{
161
162
**AppConfig.defaults,
162
163
**config.dict(exclude_none=True),
@@ -164,7 +165,7 @@ class Api:
164
165
ignored=AppConfig.ignored_providers
165
166
)
166
167
if not config.stream:
167
return JSONResponse((await response).to_json())
168
return JSONResponse(response.to_json())
168
169
169
170
async def streaming():
170
171
try:
@@ -196,10 +197,11 @@ class Api:
196
197
auth_header = auth_header.split(None, 1)[-1]
197
198
if auth_header and auth_header != "Bearer":
198
199
config.api_key = auth_header
199
response = self.client.images.generate(
200
# Use the asynchronous generate method and await it
201
response = await self.client.images.async_generate(
200
202
**config.dict(exclude_none=True),
201
203
)
202
return JSONResponse((await response).to_json())
204
return JSONResponse(response.to_json())
203
205
except Exception as e:
204
206
logging.exception(e)
205
207
return Response(content=format_exception(e, config), status_code=500, media_type="application/json")
@@ -232,4 +234,4 @@ def run_api(
232
234
use_colors=use_colors,
233
235
factory=True,
234
236
reload=debug
235
)
237
)