-
Notifications
You must be signed in to change notification settings - Fork 841
[inference provider] Add wavespeed.ai as an inference provider #3474
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
hanouticelina
merged 11 commits into
huggingface:main
from
arabot777:feat/inference_wavespeedai
Oct 28, 2025
Merged
Changes from 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
a9a73b3
init wavespeed ai
arabot777 f7c9b7d
merge main
arabot777 af525f5
python wavespeed ai
arabot777 9dcc68b
mapping
arabot777 5f05bbc
Apply style fixes
github-actions[bot] bab6a36
Merge branch 'main' into feat/inference_wavespeedai
hanouticelina 801c15e
Merge branch 'main' into feat/inference_wavespeedai
arabot777 4376c49
Merge branch 'main' into feat/inference_wavespeedai
arabot777 ae79533
Address review feedback for Wavespeed AI provider
arabot777 0427ce0
Remove redundant _prepare_headers override in WavespeedAITask
arabot777 185e79d
Apply style fixes
github-actions[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -36,6 +36,7 @@ | |
| "sambanova": {}, | ||
| "scaleway": {}, | ||
| "together": {}, | ||
| "wavespeed": {}, | ||
| "zai-org": {}, | ||
| } | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| import base64 | ||
| import time | ||
| from abc import ABC | ||
| from typing import Any, Optional, Union | ||
| from urllib.parse import urlparse | ||
|
|
||
| from huggingface_hub.hf_api import InferenceProviderMapping | ||
| from huggingface_hub.inference._common import RequestParameters, _as_dict | ||
| from huggingface_hub.inference._providers._common import TaskProviderHelper, filter_none | ||
| from huggingface_hub.utils import get_session, hf_raise_for_status | ||
| from huggingface_hub.utils.logging import get_logger | ||
|
|
||
|
|
||
| logger = get_logger(__name__) | ||
|
|
||
| # Polling interval (in seconds) | ||
| _POLLING_INTERVAL = 0.5 | ||
|
|
||
|
|
||
| class WavespeedAITask(TaskProviderHelper, ABC): | ||
| def __init__(self, task: str): | ||
| super().__init__(provider="wavespeed", base_url="https://api.wavespeed.ai", task=task) | ||
|
|
||
| def _prepare_headers(self, headers: dict, api_key: str) -> dict: | ||
| headers = super()._prepare_headers(headers, api_key) | ||
| if not api_key.startswith("hf_"): | ||
| headers["Authorization"] = f"Bearer {api_key}" | ||
| return headers | ||
|
|
||
| def _prepare_route(self, mapped_model: str, api_key: str) -> str: | ||
| return f"/api/v3/{mapped_model}" | ||
|
|
||
| def get_response( | ||
| self, | ||
| response: Union[bytes, dict], | ||
| request_params: Optional[RequestParameters] = None, | ||
| ) -> Any: | ||
| response_dict = _as_dict(response) | ||
| data = response_dict.get("data", {}) | ||
| result_path = data.get("urls", {}).get("get") | ||
|
|
||
| if not result_path: | ||
| raise ValueError("No result URL found in the response") | ||
| if request_params is None: | ||
| raise ValueError("A `RequestParameters` object should be provided to get responses with WaveSpeed AI.") | ||
|
|
||
| # Parse the request URL to determine base URL | ||
| parsed_url = urlparse(request_params.url) | ||
| # Add /wavespeed to base URL if going through HF router | ||
| if parsed_url.netloc == "router.huggingface.co": | ||
| base_url = f"{parsed_url.scheme}://{parsed_url.netloc}/wavespeed" | ||
| else: | ||
| base_url = f"{parsed_url.scheme}://{parsed_url.netloc}" | ||
|
|
||
| # Extract path from result_path URL | ||
| if isinstance(result_path, str): | ||
| result_url_path = urlparse(result_path).path | ||
| else: | ||
| result_url_path = result_path | ||
|
|
||
| result_url = f"{base_url}{result_url_path}" | ||
|
|
||
| logger.info("Processing request, polling for results...") | ||
|
|
||
| # Poll until task is completed | ||
| while True: | ||
| time.sleep(_POLLING_INTERVAL) | ||
| result_response = get_session().get(result_url, headers=request_params.headers) | ||
| hf_raise_for_status(result_response) | ||
|
|
||
| result = result_response.json() | ||
| task_result = result.get("data", {}) | ||
| status = task_result.get("status") | ||
|
|
||
| if status == "completed": | ||
| # Get content from the first output URL | ||
| if not task_result.get("outputs") or len(task_result["outputs"]) == 0: | ||
| raise ValueError("No output URL in completed response") | ||
|
|
||
| output_url = task_result["outputs"][0] | ||
| return get_session().get(output_url).content | ||
| elif status == "failed": | ||
| error_msg = task_result.get("error", "Task failed with no specific error message") | ||
| raise ValueError(f"WaveSpeed AI task failed: {error_msg}") | ||
| elif status in ["processing", "created"]: | ||
| continue | ||
| else: | ||
| raise ValueError(f"Unknown status: {status}") | ||
|
|
||
|
|
||
| class WavespeedAITextToImageTask(WavespeedAITask): | ||
| def __init__(self): | ||
| super().__init__("text-to-image") | ||
|
|
||
| def _prepare_payload_as_dict( | ||
| self, | ||
| inputs: Any, | ||
| parameters: dict, | ||
| provider_mapping_info: InferenceProviderMapping, | ||
| ) -> Optional[dict]: | ||
| return {"prompt": inputs, **filter_none(parameters)} | ||
|
|
||
|
|
||
| class WavespeedAITextToVideoTask(WavespeedAITextToImageTask): | ||
| def __init__(self): | ||
| WavespeedAITask.__init__(self, "text-to-video") | ||
|
|
||
|
|
||
| class WavespeedAIImageToImageTask(WavespeedAITask): | ||
| def __init__(self): | ||
| super().__init__("image-to-image") | ||
|
|
||
| def _prepare_payload_as_dict( | ||
| self, | ||
| inputs: Any, | ||
| parameters: dict, | ||
| provider_mapping_info: InferenceProviderMapping, | ||
| ) -> Optional[dict]: | ||
| # Convert inputs to image (URL or base64) | ||
| if isinstance(inputs, str) and inputs.startswith(("http://", "https://")): | ||
| image = inputs | ||
| elif isinstance(inputs, str): | ||
| # If input is a file path, read it first | ||
| with open(inputs, "rb") as f: | ||
| file_content = f.read() | ||
| image_b64 = base64.b64encode(file_content).decode("utf-8") | ||
| image = f"data:image/jpeg;base64,{image_b64}" | ||
| else: | ||
| # If input is binary data | ||
| image_b64 = base64.b64encode(inputs).decode("utf-8") | ||
| image = f"data:image/jpeg;base64,{image_b64}" | ||
|
|
||
| # Extract prompt from parameters if present | ||
| prompt = parameters.pop("prompt", None) | ||
| payload = {"image": image, **filter_none(parameters)} | ||
| if prompt is not None: | ||
| payload["prompt"] = prompt | ||
|
|
||
| return payload | ||
|
|
||
|
|
||
| class WavespeedAIImageToVideoTask(WavespeedAIImageToImageTask): | ||
| def __init__(self): | ||
| WavespeedAITask.__init__(self, "image-to-video") | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
no need to redefine
_prepare_headers,TaskProviderHelper. _prepare_headersalready sets the bearer prefix in the authorization headerThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@hanouticelina Done! Thanks for the thorough review!