Repository navigation
feat(provider): add Alibaba Cloud Token Plan provider #44601
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
Draft
lewisco
wants to merge
11
commits into
BerriAI:main
Choose a base branch
from
lewisco:litellm_alibaba_token_plan
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+3,865
−21
Draft
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
64048e0
feat(provider): add Alibaba Cloud Token Plan provider
lewisco a586971
refactor(provider): slim Alibaba Token Plan adapters to provider tran…
lewisco 6ac150f
docs(readme): list the Alibaba Cloud Token Plan provider
lewisco 57a7049
fix(provider): address Alibaba Token Plan review findings
lewisco dbc41e6
Merge branch 'main' into litellm_alibaba_token_plan
lewisco 5eae427
fix(provider): reject Token Plan realtime guardrail audio
lewisco e8588f2
Merge remote-tracking branch 'origin/main' into litellm_alibaba_token…
lewisco 6538bec
fix(provider): align Token Plan with main after merge
lewisco d6663e7
ci(test-unit): assign Token Plan unit tests to a shard
lewisco a1191bb
fix(provider): reject unsupported Token Plan transcription formats
lewisco e40d8af
fix(provider): keep the guardrail-checked prompt authoritative for To…
lewisco 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
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
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
137 changes: 137 additions & 0 deletions
137
litellm/llms/alibaba_token_plan/audio_transcription/transformation.py
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,137 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import base64 | ||
| from collections.abc import Mapping, Sequence | ||
| from pathlib import PurePath | ||
| from typing import Final | ||
|
|
||
| import httpx | ||
| from pydantic import BaseModel, ValidationError | ||
|
|
||
| import litellm | ||
| from litellm.exceptions import UnsupportedParamsError | ||
| from litellm.litellm_core_utils.audio_utils.utils import process_audio_file | ||
| from litellm.llms.alibaba_token_plan.common_utils import IMAGE_PATH, get_api_url, validate_headers | ||
| from litellm.llms.base_llm.audio_transcription.transformation import ( | ||
| AudioTranscriptionRequestData, | ||
| BaseAudioTranscriptionConfig, | ||
| ) | ||
| from litellm.llms.base_llm.chat.transformation import BaseLLMException | ||
| from litellm.types.llms.openai import AllMessageValues, OpenAIAudioTranscriptionOptionalParams | ||
| from litellm.types.utils import FileTypes, TranscriptionResponse, TranscriptionUsageDurationObject | ||
|
|
||
| SUPPORTED_RESPONSE_FORMATS: Final = ("json", "text") | ||
|
|
||
|
|
||
| class _TranscriptionOutput(BaseModel, frozen=True): | ||
| text: str | ||
|
|
||
|
|
||
| class _TranscriptionUsage(BaseModel, frozen=True): | ||
| duration: float | ||
|
|
||
|
|
||
| class _TranscriptionResult(BaseModel, frozen=True): | ||
| output: _TranscriptionOutput | ||
| usage: _TranscriptionUsage | None = None | ||
|
|
||
|
|
||
| class AlibabaTokenPlanAudioTranscriptionConfig(BaseAudioTranscriptionConfig): | ||
| @property | ||
| def has_native_transcription_endpoint(self) -> bool: | ||
| return True | ||
|
|
||
| def get_supported_openai_params( | ||
| self, model: str | ||
| ) -> list[OpenAIAudioTranscriptionOptionalParams]: # mutable-ok: base config requires a list | ||
| return ["language", "prompt", "response_format"] | ||
|
|
||
| def map_openai_params( | ||
| self, | ||
| non_default_params: Mapping[str, object], | ||
| optional_params: Mapping[str, object], | ||
| model: str, | ||
| drop_params: bool, | ||
| ) -> dict[str, object]: # mutable-ok: the base config contract returns mutable request parameters | ||
| response_format: Final = non_default_params.get("response_format") | ||
| unsupported: Final = response_format is not None and response_format not in SUPPORTED_RESPONSE_FORMATS | ||
| if unsupported and not (drop_params or litellm.drop_params): | ||
| raise UnsupportedParamsError( | ||
| status_code=400, | ||
| message=( | ||
| f"Alibaba Token Plan transcription does not support response_format={response_format!r}. " | ||
| f"Supported values: {', '.join(SUPPORTED_RESPONSE_FORMATS)}. " | ||
| "To drop unsupported openai params from the call, set `litellm.drop_params = True`" | ||
| ), | ||
| ) | ||
| return {**optional_params, **{k: v for k, v in non_default_params.items() if k in ("language", "prompt")}} | ||
|
|
||
| def validate_environment( | ||
| self, | ||
| headers: Mapping[str, str], | ||
| model: str, | ||
| messages: Sequence[AllMessageValues], | ||
| optional_params: Mapping[str, object], | ||
| litellm_params: Mapping[str, object], | ||
| api_key: str | None = None, | ||
| api_base: str | None = None, | ||
| ) -> dict[str, str]: # mutable-ok: the HTTP handler adds headers after validation | ||
| return validate_headers(headers, api_key) | ||
|
|
||
| def get_complete_url( | ||
| self, | ||
| api_base: str | None, | ||
| api_key: str | None, | ||
| model: str, | ||
| optional_params: Mapping[str, object], | ||
| litellm_params: Mapping[str, object], | ||
| stream: bool | None = None, | ||
| ) -> str: | ||
| return get_api_url(api_base, IMAGE_PATH) | ||
|
|
||
| def get_error_class( | ||
| self, error_message: str, status_code: int, headers: Mapping[str, str] | httpx.Headers | ||
| ) -> BaseLLMException: | ||
| return BaseLLMException(message=error_message, status_code=status_code, headers=dict(headers)) | ||
|
|
||
| def transform_audio_transcription_request( | ||
| self, | ||
| model: str, | ||
| audio_file: FileTypes, | ||
| optional_params: Mapping[str, object], | ||
| litellm_params: Mapping[str, object], | ||
| ) -> AudioTranscriptionRequestData: | ||
| audio: Final = process_audio_file(audio_file) | ||
| audio_data: Final = f"data:{audio.content_type};base64,{base64.b64encode(audio.file_content).decode('ascii')}" | ||
| prompt: Final = optional_params.get("prompt") | ||
| language: Final = optional_params.get("language") | ||
| context: Final = [{"role": "user", "content": [{"type": "input_text", "text": prompt}]}] if prompt else [] | ||
| return AudioTranscriptionRequestData( | ||
| data={ | ||
| "model": model, | ||
| "input": { | ||
| "messages": [ | ||
| *context, | ||
| {"role": "user", "content": [{"type": "input_audio", "input_audio": {"data": audio_data}}]}, | ||
| ] | ||
| }, | ||
| "parameters": { | ||
| "format": PurePath(audio.filename).suffix.lstrip(".").lower() or "wav", | ||
| **({"language_hints": [language]} if language else {}), | ||
| }, | ||
| }, | ||
| content_type="application/json", | ||
| ) | ||
|
|
||
| def transform_audio_transcription_response(self, raw_response: httpx.Response) -> TranscriptionResponse: | ||
| if not raw_response.is_success: | ||
| raise self.get_error_class(raw_response.text, raw_response.status_code, raw_response.headers) | ||
| try: | ||
| parsed: Final = _TranscriptionResult.model_validate_json(raw_response.content) | ||
| except ValidationError: | ||
| raise self.get_error_class(raw_response.text, 502, raw_response.headers) from None | ||
| response: Final = TranscriptionResponse(text=parsed.output.text) | ||
| if parsed.usage is not None: | ||
| response.usage = TranscriptionUsageDurationObject(type="duration", seconds=parsed.usage.duration) | ||
| response["duration"] = parsed.usage.duration | ||
| return response | ||
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,12 @@ | ||
| from litellm.llms.alibaba_token_plan.common_utils import get_api_base, get_api_key | ||
| from litellm.llms.dashscope.chat.transformation import DashScopeChatConfig | ||
|
|
||
|
|
||
| class AlibabaTokenPlanChatConfig(DashScopeChatConfig): | ||
| def _get_openai_compatible_provider_info( | ||
| self, api_base: str | None, api_key: str | None | ||
| ) -> tuple[str | None, str | None]: | ||
| return self._resolve_chat_api_base(api_base), get_api_key(api_key) | ||
|
|
||
| def _resolve_chat_api_base(self, api_base: str | None) -> str: | ||
| return get_api_base(api_base) |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.