返回提交历史
Modified
g4f/Provider/ReplicateHome.py
+101
-110
Modified
g4f/models.py
+19
-0
XFEstudio/gpt4free
refactor(ReplicateHome): update model handling and API interaction
d69372a9
代码差异
2 个文件
+120
-110
@@ -1,58 +1,60 @@
1
1
from __future__ import annotations
2
from typing import Generator, Optional, Dict, Any, Union, List
3
import random
2
3
import json
4
4
import asyncio
5
import base64
5
from aiohttp import ClientSession, ContentTypeError
6
6
7
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
8
7
from ..typing import AsyncResult, Messages
9
from ..requests import StreamSession, raise_for_status
10
from ..errors import ResponseError
8
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
9
from .helper import format_prompt
11
10
from ..image import ImageResponse
12
11
13
12
class ReplicateHome(AsyncGeneratorProvider, ProviderModelMixin):
14
13
url = "https://replicate.com"
15
parent = "Replicate"
14
api_endpoint = "https://homepage.replicate.com/api/prediction"
16
15
working = True
16
supports_stream = True
17
supports_system_message = True
18
supports_message_history = True
19
17
20
default_model = 'meta/meta-llama-3-70b-instruct'
18
text_models = {"meta/meta-llama-3-70b-instruct", "mistralai/mixtral-8x7b-instruct-v0.1", "google-deepmind/gemma-2b-it"}
19
image_models = {"stability-ai/stable-diffusion-3", "bytedance/sdxl-lightning-4step", "playgroundai/playground-v2.5-1024px-aesthetic"}
20
models = [
21
*text_models,
22
*image_models
21
22
text_models = [
23
'meta/meta-llama-3-70b-instruct',
24
'mistralai/mixtral-8x7b-instruct-v0.1',
25
'google-deepmind/gemma-2b-it',
26
'yorickvp/llava-13b',
23
27
]
24
28
25
versions = {
26
# Model versions for generating images
27
'stability-ai/stable-diffusion-3': [
28
"527d2a6296facb8e47ba1eaf17f142c240c19a30894f437feee9b91cc29d8e4f"
29
],
30
'bytedance/sdxl-lightning-4step': [
31
"5f24084160c9089501c1b3545d9be3c27883ae2239b6f412990e82d4a6210f8f"
32
],
33
'playgroundai/playground-v2.5-1024px-aesthetic': [
34
"a45f82a1382bed5c7aeb861dac7c7d191b0fdf74d8d57c4a0e6ed7d4d0bf7d24"
35
],
36
37
# Model versions for text generation
38
'meta/meta-llama-3-70b-instruct': [
39
"dp-cf04fe09351e25db628e8b6181276547"
40
],
41
'mistralai/mixtral-8x7b-instruct-v0.1': [
42
"dp-89e00f489d498885048e94f9809fbc76"
43
],
44
'google-deepmind/gemma-2b-it': [
45
"dff94eaf770e1fc211e425a50b51baa8e4cac6c39ef074681f9e39d778773626"
46
]
47
}
29
image_models = [
30
'black-forest-labs/flux-schnell',
31
'stability-ai/stable-diffusion-3',
32
'bytedance/sdxl-lightning-4step',
33
'playgroundai/playground-v2.5-1024px-aesthetic',
34
]
48
35
36
models = text_models + image_models
37
49
38
model_aliases = {
39
"flux-schnell": "black-forest-labs/flux-schnell",
50
40
"sd-3": "stability-ai/stable-diffusion-3",
51
41
"sdxl": "bytedance/sdxl-lightning-4step",
52
42
"playground-v2.5": "playgroundai/playground-v2.5-1024px-aesthetic",
53
43
"llama-3-70b": "meta/meta-llama-3-70b-instruct",
54
44
"mixtral-8x7b": "mistralai/mixtral-8x7b-instruct-v0.1",
55
45
"gemma-2b": "google-deepmind/gemma-2b-it",
46
"llava-13b": "yorickvp/llava-13b",
47
}
48
49
model_versions = {
50
"meta/meta-llama-3-70b-instruct": "fbfb20b472b2f3bdd101412a9f70a0ed4fc0ced78a77ff00970ee7a2383c575d",
51
"mistralai/mixtral-8x7b-instruct-v0.1": "5d78bcd7a992c4b793465bcdcf551dc2ab9668d12bb7aa714557a21c1e77041c",
52
"google-deepmind/gemma-2b-it": "dff94eaf770e1fc211e425a50b51baa8e4cac6c39ef074681f9e39d778773626",
53
"yorickvp/llava-13b": "80537f9eead1a5bfa72d5ac6ea6414379be41d4d4f6679fd776e9535d1eb58bb",
54
'black-forest-labs/flux-schnell': "f2ab8a5bfe79f02f0789a146cf5e73d2a4ff2684a98c2b303d1e1ff3814271db",
55
'stability-ai/stable-diffusion-3': "527d2a6296facb8e47ba1eaf17f142c240c19a30894f437feee9b91cc29d8e4f",
56
'bytedance/sdxl-lightning-4step': "5f24084160c9089501c1b3545d9be3c27883ae2239b6f412990e82d4a6210f8f",
57
'playgroundai/playground-v2.5-1024px-aesthetic': "a45f82a1382bed5c7aeb861dac7c7d191b0fdf74d8d57c4a0e6ed7d4d0bf7d24",
56
58
}
57
59
58
60
@classmethod
@@ -69,84 +71,73 @@ class ReplicateHome(AsyncGeneratorProvider, ProviderModelMixin):
69
71
cls,
70
72
model: str,
71
73
messages: Messages,
72
**kwargs: Any
73
) -> Generator[Union[str, ImageResponse], None, None]:
74
yield await cls.create_async(messages[-1]["content"], model, **kwargs)
75
76
@classmethod
77
async def create_async(
78
cls,
79
prompt: str,
80
model: str,
81
api_key: Optional[str] = None,
82
proxy: Optional[str] = None,
83
timeout: int = 180,
84
version: Optional[str] = None,
85
extra_data: Dict[str, Any] = {},
86
**kwargs: Any
87
) -> Union[str, ImageResponse]:
88
model = cls.get_model(model) # Use the get_model method to resolve model name
74
proxy: str = None,
75
**kwargs
76
) -> AsyncResult:
77
model = cls.get_model(model)
78
89
79
headers = {
90
'Accept-Encoding': 'gzip, deflate, br',
91
'Accept-Language': 'en-US',
92
'Connection': 'keep-alive',
93
'Origin': cls.url,
94
'Referer': f'{cls.url}/',
95
'Sec-Fetch-Dest': 'empty',
96
'Sec-Fetch-Mode': 'cors',
97
'Sec-Fetch-Site': 'same-site',
98
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
99
'sec-ch-ua': '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
100
'sec-ch-ua-mobile': '?0',
101
'sec-ch-ua-platform': '"macOS"',
80
"accept": "*/*",
81
"accept-language": "en-US,en;q=0.9",
82
"cache-control": "no-cache",
83
"content-type": "application/json",
84
"origin": "https://replicate.com",
85
"pragma": "no-cache",
86
"priority": "u=1, i",
87
"referer": "https://replicate.com/",
88
"sec-ch-ua": '"Not;A=Brand";v="24", "Chromium";v="128"',
89
"sec-ch-ua-mobile": "?0",
90
"sec-ch-ua-platform": '"Linux"',
91
"sec-fetch-dest": "empty",
92
"sec-fetch-mode": "cors",
93
"sec-fetch-site": "same-site",
94
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
102
95
}
103
104
if version is None:
105
version = random.choice(cls.versions.get(model, []))
106
if api_key is not None:
107
headers["Authorization"] = f"Bearer {api_key}"
108
109
async with StreamSession(
110
proxies={"all": proxy},
111
headers=headers,
112
timeout=timeout
113
) as session:
96
97
async with ClientSession(headers=headers) as session:
98
if model in cls.image_models:
99
prompt = messages[-1]['content'] if messages else ""
100
else:
101
prompt = format_prompt(messages)
102
114
103
data = {
115
"input": {
116
"prompt": prompt,
117
**extra_data
118
},
119
"version": version
104
"model": model,
105
"version": cls.model_versions[model],
106
"input": {"prompt": prompt},
120
107
}
121
if api_key is None:
122
data["model"] = model
123
url = "https://homepage.replicate.com/api/prediction"
124
else:
125
url = "https://api.replicate.com/v1/predictions"
126
async with session.post(url, json=data) as response:
127
await raise_for_status(response)
108
109
async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
110
response.raise_for_status()
128
111
result = await response.json()
129
if "id" not in result:
130
raise ResponseError(f"Invalid response: {result}")
112
prediction_id = result['id']
113
114
poll_url = f"https://homepage.replicate.com/api/poll?id={prediction_id}"
115
max_attempts = 30
116
delay = 5
117
for _ in range(max_attempts):
118
async with session.get(poll_url, proxy=proxy) as response:
119
response.raise_for_status()
120
try:
121
result = await response.json()
122
except ContentTypeError:
123
text = await response.text()
124
try:
125
result = json.loads(text)
126
except json.JSONDecodeError:
127
raise ValueError(f"Unexpected response format: {text}")
131
128
132
while True:
133
if api_key is None:
134
url = f"https://homepage.replicate.com/api/poll?id={result['id']}"
135
else:
136
url = f"https://api.replicate.com/v1/predictions/{result['id']}"
137
async with session.get(url) as response:
138
await raise_for_status(response)
139
result = await response.json()
140
if "status" not in result:
141
raise ResponseError(f"Invalid response: {result}")
142
if result["status"] == "succeeded":
143
output = result['output']
144
if model in cls.text_models:
145
return ''.join(output) if isinstance(output, list) else output
146
elif model in cls.image_models:
147
images: List[Any] = output
148
images = images[0] if len(images) == 1 else images
149
return ImageResponse(images, prompt)
150
elif result["status"] == "failed":
151
raise ResponseError(f"Prediction failed: {result}")
152
await asyncio.sleep(0.5)
129
if result['status'] == 'succeeded':
130
if model in cls.image_models:
131
image_url = result['output'][0]
132
yield ImageResponse(image_url, "Generated image")
133
return
134
else:
135
for chunk in result['output']:
136
yield chunk
137
break
138
elif result['status'] == 'failed':
139
raise Exception(f"Prediction failed: {result.get('error')}")
140
await asyncio.sleep(delay)
141
142
if result['status'] != 'succeeded':
143
raise Exception("Prediction timed out")
@@ -489,6 +489,13 @@ sh_n_7b = Model(
489
489
best_provider = Airforce
490
490
)
491
491
492
### Yorickvp ###
493
llava_13b = Model(
494
name = 'llava-13b',
495
base_provider = 'Yorickvp',
496
best_provider = ReplicateHome
497
)
498
492
499
#############
493
500
### Image ###
494
501
#############
@@ -559,6 +566,13 @@ flux_pixel = Model(
559
566
560
567
)
561
568
569
flux_schnell = Model(
570
name = 'flux-schnell',
571
base_provider = 'Flux AI',
572
best_provider = IterListProvider([ReplicateHome])
573
574
)
575
562
576
### ###
563
577
dalle = Model(
564
578
name = 'dalle',
@@ -746,6 +760,10 @@ class ModelUtils:
746
760
747
761
### Together ###
748
762
'sh-n-7b': sh_n_7b,
763
764
765
### Yorickvp ###
766
'llava-13b': llava_13b,
749
767
750
768
751
769
@@ -769,6 +787,7 @@ class ModelUtils:
769
787
'flux-3d': flux_3d,
770
788
'flux-disney': flux_disney,
771
789
'flux-pixel': flux_pixel,
790
'flux-schnell': flux_schnell,
772
791
773
792
774
793
### ###