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 3 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
122 changes: 122 additions & 0 deletions
122
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,122 @@ | ||
| 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 | ||
|
|
||
| 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 | ||
|
|
||
|
|
||
| class _TranscriptionOutput(BaseModel): | ||
| text: str | ||
|
|
||
|
|
||
| class _TranscriptionUsage(BaseModel): | ||
| duration: float | ||
|
|
||
|
|
||
| class _TranscriptionResult(BaseModel): | ||
| 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 | ||
| 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) |
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,65 @@ | ||
| import base64 | ||
| from collections.abc import Mapping | ||
| from os import PathLike | ||
| from pathlib import Path | ||
| from typing import Final, Protocol, runtime_checkable | ||
|
|
||
| import litellm | ||
| from litellm.images.utils import ImageEditRequestUtils | ||
| from litellm.secret_managers.main import get_secret_str | ||
|
|
||
| DEFAULT_API_BASE: Final = "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1" | ||
| MESSAGES_PATH: Final = "apps/anthropic" | ||
| IMAGE_PATH: Final = "api/v1/services/aigc/multimodal-generation/generation" | ||
| SPEECH_PATH: Final = "api/v1/services/audio/tts/SpeechSynthesizer" | ||
| REALTIME_PATH: Final = "api-ws/v1/realtime" | ||
| VIDEO_PATH: Final = "api/v1/services/aigc/video-generation/video-synthesis" | ||
|
|
||
|
|
||
| @runtime_checkable | ||
| class _Readable(Protocol): | ||
| def read(self) -> bytes: ... | ||
|
|
||
|
|
||
| def get_api_key(api_key: str | None) -> str | None: | ||
| return api_key or get_secret_str("ALIBABA_TOKEN_PLAN_API_KEY") or litellm.api_key | ||
|
|
||
|
|
||
| def require_api_key(api_key: str | None) -> str: | ||
| resolved_key: Final = get_api_key(api_key) | ||
| if not resolved_key: | ||
| raise litellm.AuthenticationError( | ||
| message="ALIBABA_TOKEN_PLAN_API_KEY is not set; provide a Token Plan api_key", | ||
| llm_provider="alibaba_token_plan", | ||
| model="", | ||
| ) | ||
| return resolved_key | ||
|
|
||
|
|
||
| def get_api_base(api_base: str | None) -> str: | ||
| return (api_base or get_secret_str("ALIBABA_TOKEN_PLAN_API_BASE") or DEFAULT_API_BASE).rstrip("/") | ||
|
|
||
|
|
||
| def get_api_url(api_base: str | None, path: str) -> str: | ||
|
greptile-apps[bot] marked this conversation as resolved.
Resolved
|
||
| return f"{get_api_base(api_base).removesuffix('/compatible-mode/v1')}/{path}" | ||
|
|
||
|
|
||
| def validate_headers( | ||
| headers: Mapping[str, str], api_key: str | None | ||
| ) -> dict[str, str]: # mutable-ok: provider interface requires a mutable return value | ||
| return {**headers, "Authorization": f"Bearer {require_api_key(api_key)}", "Content-Type": "application/json"} | ||
|
|
||
|
|
||
| def image_reference(image: object) -> str: | ||
| if isinstance(image, str): | ||
| return image | ||
| if isinstance(image, tuple) and len(image) > 1: | ||
| return image_reference(image[1]) | ||
| if isinstance(image, PathLike): | ||
| return image_reference(Path(image).read_bytes()) | ||
| if isinstance(image, _Readable): | ||
| return image_reference(image.read()) | ||
| if not isinstance(image, bytes): | ||
| raise TypeError("Image must be a URL, data URI, bytes, path or binary file") | ||
| content_type: Final = ImageEditRequestUtils.get_image_content_type(image) | ||
| return f"data:{content_type};base64,{base64.b64encode(image).decode('ascii')}" | ||
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.