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

XFEstudio/gpt4free

New provider added (g4f/Provider/Chatai.py) (#2864)

* Update __init__.py to include the new provider new provider Chatai * Create chatai.py * Rename chatai.py to Chatai.py * Resolve the conflict in __init__.py --------- Co-authored-by: H Lohaus <hlohaus@users.noreply.github.com>

fa36dccf
Zetsu4i <79372809+Zetsu4i@users.noreply.github.com>
提交于

代码差异

2 个文件 +141 -0
Added g4f/Provider/Chatai.py +140 -0
@@ -0,0 +1,140 @@
1 from __future__ import annotations
2
3 import json
4 import random
5 import string
6
7 from aiohttp import ClientSession
8 from .. import debug
9
10 from ..typing import AsyncResult, Messages
11 from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
12
13 def generate_machine_id() :
14 """
15 generates random machine id
16 Returns:
17 str: machine id
18 """
19 part1 = "".join(random.choices(string.digits, k=16))
20 part2 = "".join(random.choices(string.digits + ".", k=25))
21 return f"{part1}.{part2}"
22
23
24 class Chatai(AsyncGeneratorProvider, ProviderModelMixin):
25 """
26 Provider for Chatai
27 """
28 label = "Chatai"
29 url = "https://chatai.aritek.app" # Base URL
30 api_endpoint = "https://chatai.aritek.app/stream" # API endpoint for chat
31 working = True
32 needs_auth = False
33 supports_stream = True
34 supports_system_message = True
35 supports_message_history = True
36
37 default_model = 'gpt-4o-mini-2024-07-18'
38 models = ['gpt-4o-mini-2024-07-18'] #
39
40 model_aliases = {"gpt-4o-mini":default_model}
41
42 # --- ProviderModelMixin Methods ---
43 @classmethod
44 def get_model(cls, model: str) -> str:
45 if model in cls.models or model == cls.default_model:
46 return cls.default_model
47 else:
48 # Fallback to default if requested model is unknown
49 return cls.default_model
50
51 # --- AsyncGeneratorProvider Method ---
52 @classmethod
53 async def create_async_generator(
54 cls,
55 model: str,
56 messages: Messages,
57 proxy: str | None = None,
58 **kwargs
59 ) -> AsyncResult:
60 """
61 Make an asynchronous request to the Chatai stream API.
62
63 Args:
64 model (str): The model name (currently ignored by this provider).
65 messages (Messages): List of message dictionaries.
66 proxy (str | None): Optional proxy URL.
67 **kwargs: Additional arguments (currently unused).
68
69 Yields:
70 str: Chunks of the response text.
71
72 Raises:
73 Exception: If the API request fails.
74 """
75
76 # selected_model = cls.get_model(model) # Not sent in payload
77
78 headers = {
79 'Accept': 'text/event-stream',
80 'Content-Type': 'application/json',
81 'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 7.1.2; SM-G935F Build/N2G48H)',
82 'Host': 'chatai.aritek.app',
83 'Connection': 'Keep-Alive',
84 }
85
86 static_machine_id = generate_machine_id()#"0343578260151264.464241743263788731"
87 c_token = "eyJzdWIiOiIyMzQyZmczNHJ0MzR0MzQiLCJuYW1lIjoiSm9objM0NTM0NT"# might change
88
89 payload = {
90 "machineId": static_machine_id,
91 "msg": messages, # Pass the message list directly
92 "token": c_token,
93 "type": 0
94 }
95
96 async with ClientSession(headers=headers) as session:
97 try:
98 async with session.post(
99 cls.api_endpoint,
100 json=payload,
101 proxy=proxy
102 ) as response:
103 response.raise_for_status() # Check for HTTP errors (4xx, 5xx)
104
105 # Process the Server-Sent Events (SSE) stream
106 async for line_bytes in response.content:
107 if not line_bytes:
108 continue # Skip empty linesw
109
110 line = line_bytes.decode('utf-8').strip()
111
112 if line.startswith("data:"):
113 data_str = line[len("data:"):].strip()
114
115 if data_str == "[DONE]":
116 break # End of stream signal
117
118 try:
119 chunk_data = json.loads(data_str)
120 choices = chunk_data.get("choices", [])
121 if choices:
122 delta = choices[0].get("delta", {})
123 content_chunk = delta.get("content")
124 if content_chunk:
125 yield content_chunk
126 # Check for finish reason if needed (e.g., to stop early)
127 # finish_reason = choices[0].get("finish_reason")
128 # if finish_reason:
129 # break
130 except json.JSONDecodeError:
131 debug.error(f"Warning: Could not decode JSON: {data_str}")
132 continue
133 except Exception as e:
134 debug.error(f"Warning: Error processing chunk: {e}")
135 continue
136
137 except Exception as e:
138 # print()
139 debug.error(f"Error during Chatai API request: {e}")
140 raise e
Modified g4f/Provider/__init__.py +1 -0
@@ -33,6 +33,7 @@ try:
33 33 from .AllenAI import AllenAI
34 34 from .ARTA import ARTA
35 35 from .Blackbox import Blackbox
36 from .Chatai import Chatai
36 37 from .ChatGLM import ChatGLM
37 38 from .ChatGpt import ChatGpt
38 39 from .ChatGptEs import ChatGptEs