File size: 11,955 Bytes
870ab6b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
import os
import time
import json
import random
import string
import asyncio
import async_timeout
import aiohttp, aiofiles
import requests
import pytz
import logging
from datetime import datetime
from fastapi import FastAPI, Request
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse, StreamingResponse
from starlette.middleware.cors import CORSMiddleware
from typing import Any
import g4f
from g4f import ChatCompletion, Provider, BaseProvider
from g4f.models import ModelUtils
from cachetools import LRUCache
import aiofiles
import async_timeout
from fp.fp import FreeProxy
from embedding_processing import embedding_processing
import concurrent.futures
app = FastAPI()
embedding_proc = embedding_processing()
LOG = logging.getLogger(__name__)
app.add_middleware(GZipMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
def get_proxy():
proxy = FreeProxy(rand=True, timeout=1).get()
return proxy
@app.post("/chat/completions")
@app.post("/v1/chat/completions")
async def chat_completions(request: Request):
req_data = await request.json()
stream = req_data.get('stream', False)
model = req_data.get('model', 'gpt-3.5-turbo')
messages = req_data.get('messages')
temperature = req_data.get('temperature', 1.0)
top_p = req_data.get('top_p', 1.0)
max_tokens = req_data.get('max_tokens', 4096)
response = ChatCompletion.create(model=model, stream=stream, messages=messages, temperature=temperature, top_p=top_p, max_tokens=max_tokens, system_prompt="")
completion_id = "".join(random.choices(string.ascii_letters + string.digits, k=28))
completion_timestamp = int(time.time())
if not stream:
return {
"id": f"chatcmpl-{completion_id}",
"object": "chat.completion",
"created": completion_timestamp,
"model": model,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": response,
},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": None,
"completion_tokens": None,
"total_tokens": None,
},
}
def streaming():
for chunk in response:
completion_data = {
"id": f"chatcmpl-{completion_id}",
"object": "chat.completion.chunk",
"created": completion_timestamp,
"model": model,
"choices": [
{
"index": 0,
"delta": {
"content": chunk,
},
"finish_reason": None,
}
],
}
content = json.dumps(completion_data, separators=(",", ":"))
yield f"data: {content}\n\n"
time.sleep(0.1)
end_completion_data: dict[str, Any] = {
"id": f"chatcmpl-{completion_id}",
"object": "chat.completion.chunk",
"created": completion_timestamp,
"model": model,
"choices": [
{
"index": 0,
"delta": {},
"finish_reason": "stop",
}
],
}
content = json.dumps(end_completion_data, separators=(",", ":"))
yield f"data: {content}\n\n"
return StreamingResponse(streaming(), media_type='text/event-stream')
@app.post('/v1/embeddings')
async def create_embedding(request: Request):
j_input = await request.json()
#model = embedding_processing()
embedding = embedding_proc.embedding(text_list=j_input['input'])
await log_event()
return JSONResponse(
embedding
)
async def log_event():
LOG.info('served')
@app.post("/v1/completions")
async def completions(request: Request):
req_data = await request.json()
model = req_data.get('model', 'text-davinci-003')
prompt = req_data.get('prompt')
messages = req_data.get('messages')
temperature = req_data.get('temperature', 1.0)
top_p = req_data.get('top_p', 1.0)
max_tokens = req_data.get('max_tokens', 4096)
response = g4f.Completion.create(model='text-davinci-003', prompt=prompt, temperature=temperature, top_p=top_p, max_tokens=max_tokens,)
completion_id = "".join(random.choices(string.ascii_letters + string.digits, k=24))
completion_timestamp = int(time.time())
return {
"id": f"cmpl-{completion_id}",
"object": "text_completion",
"created": completion_timestamp,
"model": "text-davinci-003",
"choices": [
{
"text": response,
"index": 0,
"logprobs": None,
"finish_reason": "length"
}
],
"usage": {
"prompt_tokens": None,
"completion_tokens": None,
"total_tokens": None
}
}
@app.get("/v1/dashboard/billing/subscription")
@app.get("/dashboard/billing/subscription")
async def billing_subscription():
return JSONResponse({
"object": "billing_subscription",
"has_payment_method": True,
"canceled": False,
"canceled_at": None,
"delinquent": None,
"access_until": 2556028800,
"soft_limit": 6944500,
"hard_limit": 166666666,
"system_hard_limit": 166666666,
"soft_limit_usd": 416.67,
"hard_limit_usd": 9999.99996,
"system_hard_limit_usd": 9999.99996,
"plan": {
"title": "Pay-as-you-go",
"id": "payg"
},
"primary": True,
"account_name": "OpenAI",
"po_number": None,
"billing_email": None,
"tax_ids": None,
"billing_address": {
"city": "New York",
"line1": "OpenAI",
"country": "US",
"postal_code": "NY10031"
},
"business_address": None
})
@app.get("/v1/dashboard/billing/usage")
@app.get("/dashboard/billing/usage")
async def billing_usage():
return JSONResponse({
"object": "list",
"daily_costs": [
{
"timestamp": time.time(),
"line_items": [
{
"name": "GPT-4",
"cost": 0.0
},
{
"name": "Chat models",
"cost": 1.01
},
{
"name": "InstructGPT",
"cost": 0.0
},
{
"name": "Fine-tuning models",
"cost": 0.0
},
{
"name": "Embedding models",
"cost": 0.0
},
{
"name": "Image models",
"cost": 16.0
},
{
"name": "Audio models",
"cost": 0.0
}
]
}
],
"total_usage": 1.01
})
@app.get("/v1/models")
@app.get("/models")
async def get_models():
models_data = {"data": []}
for model_name, model in ModelUtils.convert.items():
models_data['data'].append({
"id": model_name,
"object": "model",
"owned_by": model.base_provider,
"tokens": 99999,
"fallbacks": None,
"endpoints": [
"/v1/chat/completions"
],
"limits": None,
"permission": []
})
return JSONResponse(models_data)
@app.get("/v1/providers")
@app.get("/providers")
async def get_providers():
providers_data = {"data": []}
for provider_name in dir(Provider):
if not provider_name.startswith('__'):
try:
provider = getattr(Provider, provider_name)
providers_data["data"].append({
"provider": provider_name,
"model": list(provider.model),
"url": provider.url,
"working": bool(provider.working),
"supports_stream": bool(provider.supports_stream)
})
except:
pass
return JSONResponse(providers_data)
def process_provider(provider_name, model_name):
try:
p = getattr(g4f.Provider, provider_name)
provider_status = {
"provider": provider_name,
"model": model_name,
"url": p.url,
"status": ""
}
# Проверяем только модель 'gpt-3.5-turbo' для провайдеров Wewordle и Qidinam
if provider_name in ['Wewordle', 'Qidinam', 'DeepAi', 'GetGpt', 'Yqcloud'] and model_name != 'gpt-3.5-turbo':
provider_status['status'] = 'Inactive'
#print(f"{provider_name} with {model_name} skipped")
return provider_status
try:
response = ChatCompletion.create(model=model_name, provider=p,
messages=[{"role": "user", "content": "Say 'Hello World!'"}], stream=False)
if any(word in response for word in ['Hello World', 'Hello', 'hello', 'world']):
provider_status['status'] = 'Active'
#print(f"{provider_name} with {model_name} say: {response}")
else:
provider_status['status'] = 'Inactive'
#print(f"{provider_name} with {model_name} say: Inactive")
except Exception as e:
provider_status['status'] = 'Inactive'
# print(f"{provider_name} with {model_name} say: Error")
return provider_status
except:
return None
async def run_check_script():
session = aiohttp.ClientSession()
while True:
models = [model for model in g4f.models.ModelUtils.convert if model.startswith('gpt-') or model.startswith('claude') or model.startswith('text-')]
providers = [provider for provider in dir(g4f.Provider) if not provider.startswith('__')]
status = {'data': []}
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = []
for provider_name in providers:
for model_name in models:
future = executor.submit(process_provider, provider_name, model_name)
futures.append(future)
for future in concurrent.futures.as_completed(futures):
result = future.result()
if result is not None and result['status'] == 'Active':
status['data'].append(result)
print(status)
status['key'] = "test"
tz = pytz.timezone('Asia/Shanghai')
now = datetime.now(tz)
print(now)
status['time'] = now.strftime("%Y-%m-%d %H:%M:%S")
if status['data']:
# Здесь мы используем aiofiles для асинхронного записывания в файл
async with aiofiles.open('status.json', 'w') as f:
await f.write(json.dumps(status))
# Pause for 5 minutes before starting the next cycle
time.sleep(360)
# Запуск асинхронных задач
async def run_tasks():
while True:
await asyncio.gather(run_check_script())
await asyncio.sleep(300)
# Запуск приложения
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(run_tasks())
loop.close()
if __name__ == "__main__":
main() |