Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/__init__.pyAdded
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/_async_client.pyAdded
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/__init__.pyAdded+204
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/audio_classification.pyAdded+43
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/audio_to_audio.pyAdded+30
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/automatic_speech_recognition.pyAdded+113
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/base.pyAdded+167
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/chat_completion.pyAdded+347
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/depth_estimation.pyAdded+28
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/document_question_answering.pyAdded+80
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/feature_extraction.pyAdded+36
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/fill_mask.pyAdded+47
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_classification.pyAdded+43
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_segmentation.pyAdded+51
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_text_to_image.pyAdded+67
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_text_to_video.pyAdded+65
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_to_image.pyAdded+60
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_to_text.pyAdded+100
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_to_video.pyAdded+60
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/object_detection.pyAdded+56
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/question_answering.pyAdded+72
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/sentence_similarity.pyAdded+27
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/summarization.pyAdded+41
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/table_question_answering.pyAdded+62
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text2text_generation.pyAdded+42
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_classification.pyAdded+41
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_generation.pyAdded+168
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_to_audio.pyAdded+99
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_to_image.pyAdded+50
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_to_speech.pyAdded+99
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_to_video.pyAdded+46
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/token_classification.pyAdded+51
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/translation.pyAdded+49
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/video_classification.pyAdded+45
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/visual_question_answering.pyAdded+49
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/zero_shot_classification.pyAdded+43
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/zero_shot_image_classification.pyAdded+38
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/zero_shot_object_detection.pyAdded+50
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/__init__.pyAdded
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/_cli_hacks.pyAdded+88
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/agent.pyAdded+100
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/cli.pyAdded+255
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/constants.pyAdded+81
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/mcp_client.pyAdded+395
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/types.pyAdded+45
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/utils.pyAdded+130
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_providers/__init__.pyAdded+270
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_providers/_common.pyAdded+364
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_providers/black_forest_labs.pyAdded+69
- .cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_providers/cerebras.pyAdded+6
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204# This file is auto-generated by `utils/generate_inference_types.py`.# Do not modify it manually.## ruff: noqa: F401
from .audio_classification import ( AudioClassificationInput, AudioClassificationOutputElement, AudioClassificationOutputTransform, AudioClassificationParameters,)from .audio_to_audio import AudioToAudioInput, AudioToAudioOutputElementfrom .automatic_speech_recognition import ( AutomaticSpeechRecognitionEarlyStoppingEnum, AutomaticSpeechRecognitionGenerationParameters, AutomaticSpeechRecognitionInput, AutomaticSpeechRecognitionOutput, AutomaticSpeechRecognitionOutputChunk, AutomaticSpeechRecognitionParameters,)from .base import BaseInferenceTypefrom .chat_completion import ( ChatCompletionInput, ChatCompletionInputFunctionDefinition, ChatCompletionInputFunctionName, ChatCompletionInputGrammarType, ChatCompletionInputJSONSchema, ChatCompletionInputMessage, ChatCompletionInputMessageChunk, ChatCompletionInputMessageChunkType, ChatCompletionInputResponseFormatJSONObject, ChatCompletionInputResponseFormatJSONSchema, ChatCompletionInputResponseFormatText, ChatCompletionInputStreamOptions, ChatCompletionInputTool, ChatCompletionInputToolCall, ChatCompletionInputToolChoiceClass, ChatCompletionInputToolChoiceEnum, ChatCompletionInputURL, ChatCompletionOutput, ChatCompletionOutputComplete, ChatCompletionOutputFunctionDefinition, ChatCompletionOutputLogprob, ChatCompletionOutputLogprobs, ChatCompletionOutputMessage, ChatCompletionOutputToolCall, ChatCompletionOutputTopLogprob, ChatCompletionOutputUsage, ChatCompletionStreamOutput, ChatCompletionStreamOutputChoice, ChatCompletionStreamOutputDelta, ChatCompletionStreamOutputDeltaToolCall, ChatCompletionStreamOutputFunction, ChatCompletionStreamOutputLogprob, ChatCompletionStreamOutputLogprobs, ChatCompletionStreamOutputTopLogprob, ChatCompletionStreamOutputUsage,)from .depth_estimation import DepthEstimationInput, DepthEstimationOutputfrom .document_question_answering import ( DocumentQuestionAnsweringInput, DocumentQuestionAnsweringInputData, DocumentQuestionAnsweringOutputElement, DocumentQuestionAnsweringParameters,)from .feature_extraction import FeatureExtractionInput, FeatureExtractionInputTruncationDirectionfrom .fill_mask import FillMaskInput, FillMaskOutputElement, FillMaskParametersfrom .image_classification import ( ImageClassificationInput, ImageClassificationOutputElement, ImageClassificationOutputTransform, ImageClassificationParameters,)from .image_segmentation import ( ImageSegmentationInput, ImageSegmentationOutputElement, ImageSegmentationParameters, ImageSegmentationSubtask,)from .image_text_to_image import ( ImageTextToImageInput, ImageTextToImageOutput, ImageTextToImageParameters, ImageTextToImageTargetSize,)from .image_text_to_video import ( ImageTextToVideoInput, ImageTextToVideoOutput, ImageTextToVideoParameters, ImageTextToVideoTargetSize,)from .image_to_image import ImageToImageInput, ImageToImageOutput, ImageToImageParameters, ImageToImageTargetSizefrom .image_to_text import ( ImageToTextEarlyStoppingEnum, ImageToTextGenerationParameters, ImageToTextInput, ImageToTextOutput, ImageToTextParameters,)from .image_to_video import ImageToVideoInput, ImageToVideoOutput, ImageToVideoParameters, ImageToVideoTargetSizefrom .object_detection import ( ObjectDetectionBoundingBox, ObjectDetectionInput, ObjectDetectionOutputElement, ObjectDetectionParameters,)from .question_answering import ( QuestionAnsweringInput, QuestionAnsweringInputData, QuestionAnsweringOutputElement, QuestionAnsweringParameters,)from .sentence_similarity import SentenceSimilarityInput, SentenceSimilarityInputDatafrom .summarization import ( SummarizationInput, SummarizationOutput, SummarizationParameters, SummarizationTruncationStrategy,)from .table_question_answering import ( Padding, TableQuestionAnsweringInput, TableQuestionAnsweringInputData, TableQuestionAnsweringOutputElement, TableQuestionAnsweringParameters,)from .text2text_generation import ( Text2TextGenerationInput, Text2TextGenerationOutput, Text2TextGenerationParameters, Text2TextGenerationTruncationStrategy,)from .text_classification import ( TextClassificationInput, TextClassificationOutputElement, TextClassificationOutputTransform, TextClassificationParameters,)from .text_generation import ( TextGenerationInput, TextGenerationInputGenerateParameters, TextGenerationInputGrammarType, TextGenerationOutput, TextGenerationOutputBestOfSequence, TextGenerationOutputDetails, TextGenerationOutputFinishReason, TextGenerationOutputPrefillToken, TextGenerationOutputToken, TextGenerationStreamOutput, TextGenerationStreamOutputStreamDetails, TextGenerationStreamOutputToken, TypeEnum,)from .text_to_audio import ( TextToAudioEarlyStoppingEnum, TextToAudioGenerationParameters, TextToAudioInput, TextToAudioOutput, TextToAudioParameters,)from .text_to_image import TextToImageInput, TextToImageOutput, TextToImageParametersfrom .text_to_speech import ( TextToSpeechEarlyStoppingEnum, TextToSpeechGenerationParameters, TextToSpeechInput, TextToSpeechOutput, TextToSpeechParameters,)from .text_to_video import TextToVideoInput, TextToVideoOutput, TextToVideoParametersfrom .token_classification import ( TokenClassificationAggregationStrategy, TokenClassificationInput, TokenClassificationOutputElement, TokenClassificationParameters,)from .translation import TranslationInput, TranslationOutput, TranslationParameters, TranslationTruncationStrategyfrom .video_classification import ( VideoClassificationInput, VideoClassificationOutputElement, VideoClassificationOutputTransform, VideoClassificationParameters,)from .visual_question_answering import ( VisualQuestionAnsweringInput, VisualQuestionAnsweringInputData, VisualQuestionAnsweringOutputElement, VisualQuestionAnsweringParameters,)from .zero_shot_classification import ( ZeroShotClassificationInput, ZeroShotClassificationOutputElement, ZeroShotClassificationParameters,)from .zero_shot_image_classification import ( ZeroShotImageClassificationInput, ZeroShotImageClassificationOutputElement, ZeroShotImageClassificationParameters,)from .zero_shot_object_detection import ( ZeroShotObjectDetectionBoundingBox, ZeroShotObjectDetectionInput, ZeroShotObjectDetectionOutputElement, ZeroShotObjectDetectionParameters,)12345678910111213141516171819202122232425262728293031323334353637383940414243# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Literal, Optional
from .base import BaseInferenceType, dataclass_with_extra
AudioClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
@dataclass_with_extraclass AudioClassificationParameters(BaseInferenceType): """Additional inference parameters for Audio Classification"""
function_to_apply: Optional["AudioClassificationOutputTransform"] = None """The function to apply to the model outputs in order to retrieve the scores.""" top_k: int | None = None """When specified, limits the output to the top K most probable classes."""
@dataclass_with_extraclass AudioClassificationInput(BaseInferenceType): """Inputs for Audio Classification inference"""
inputs: str """The input audio data as a base64-encoded string. If no `parameters` are provided, you can also provide the audio data as a raw bytes payload. """ parameters: AudioClassificationParameters | None = None """Additional inference parameters for Audio Classification"""
@dataclass_with_extraclass AudioClassificationOutputElement(BaseInferenceType): """Outputs for Audio Classification inference"""
label: str """The predicted class label.""" score: float """The corresponding probability."""123456789101112131415161718192021222324252627282930# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass AudioToAudioInput(BaseInferenceType): """Inputs for Audio to Audio inference"""
inputs: Any """The input audio data"""
@dataclass_with_extraclass AudioToAudioOutputElement(BaseInferenceType): """Outputs of inference for the Audio To Audio task A generated audio file with its label. """
blob: Any """The generated audio file.""" content_type: str """The content type of audio file.""" label: str """The label of the audio file."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Literal, Union
from .base import BaseInferenceType, dataclass_with_extra
AutomaticSpeechRecognitionEarlyStoppingEnum = Literal["never"]
@dataclass_with_extraclass AutomaticSpeechRecognitionGenerationParameters(BaseInferenceType): """Parametrization of the text generation process"""
do_sample: bool | None = None """Whether to use sampling instead of greedy decoding when generating new tokens.""" early_stopping: Union[bool, "AutomaticSpeechRecognitionEarlyStoppingEnum"] | None = None """Controls the stopping condition for beam-based methods.""" epsilon_cutoff: float | None = None """If set to float strictly between 0 and 1, only tokens with a conditional probability greater than epsilon_cutoff will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) for more details. """ eta_cutoff: float | None = None """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) for more details. """ max_length: int | None = None """The maximum length (in tokens) of the generated text, including the input.""" max_new_tokens: int | None = None """The maximum number of tokens to generate. Takes precedence over max_length.""" min_length: int | None = None """The minimum length (in tokens) of the generated text, including the input.""" min_new_tokens: int | None = None """The minimum number of tokens to generate. Takes precedence over min_length.""" num_beam_groups: int | None = None """Number of groups to divide num_beams into in order to ensure diversity among different groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details. """ num_beams: int | None = None """Number of beams to use for beam search.""" penalty_alpha: float | None = None """The value balances the model confidence and the degeneration penalty in contrastive search decoding. """ temperature: float | None = None """The value used to modulate the next token probabilities.""" top_k: int | None = None """The number of highest probability vocabulary tokens to keep for top-k-filtering.""" top_p: float | None = None """If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. """ typical_p: float | None = None """Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to typical_p or higher are kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details. """ use_cache: bool | None = None """Whether the model should use the past last key/values attentions to speed up decoding"""
@dataclass_with_extraclass AutomaticSpeechRecognitionParameters(BaseInferenceType): """Additional inference parameters for Automatic Speech Recognition"""
generation_parameters: AutomaticSpeechRecognitionGenerationParameters | None = None """Parametrization of the text generation process""" return_timestamps: bool | None = None """Whether to output corresponding timestamps with the generated text"""
@dataclass_with_extraclass AutomaticSpeechRecognitionInput(BaseInferenceType): """Inputs for Automatic Speech Recognition inference"""
inputs: str """The input audio data as a base64-encoded string. If no `parameters` are provided, you can also provide the audio data as a raw bytes payload. """ parameters: AutomaticSpeechRecognitionParameters | None = None """Additional inference parameters for Automatic Speech Recognition"""
@dataclass_with_extraclass AutomaticSpeechRecognitionOutputChunk(BaseInferenceType): text: str """A chunk of text identified by the model""" timestamp: list[float] """The start and end timestamps corresponding with the text"""
@dataclass_with_extraclass AutomaticSpeechRecognitionOutput(BaseInferenceType): """Outputs of inference for the Automatic Speech Recognition task"""
text: str """The recognized text.""" chunks: list[AutomaticSpeechRecognitionOutputChunk] | None = None """When returnTimestamps is enabled, chunks contains a list of audio chunks identified by the model. """123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167# Copyright 2024 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Contains a base class for all inference types."""
import inspectimport jsonimport typesfrom dataclasses import asdict, dataclassfrom typing import Any, TypeVar, get_args
from typing_extensions import dataclass_transform
T = TypeVar("T", bound="BaseInferenceType")
def _repr_with_extra(self): fields = list(self.__dataclass_fields__.keys()) other_fields = list(k for k in self.__dict__ if k not in fields) return f"{self.__class__.__name__}({', '.join(f'{k}={self.__dict__[k]!r}' for k in fields + other_fields)})"
@dataclass_transform()def dataclass_with_extra(cls: type[T]) -> type[T]: """Decorator to add a custom __repr__ method to a dataclass, showing all fields, including extra ones.
This decorator only works with dataclasses that inherit from `BaseInferenceType`. """ cls = dataclass(cls) cls.__repr__ = _repr_with_extra # type: ignore[method-assign] return cls
@dataclassclass BaseInferenceType(dict): """Base class for all inference types.
Object is a dataclass and a dict for backward compatibility but plan is to remove the dict part in the future.
Handle parsing from dict, list and json strings in a permissive way to ensure future-compatibility (e.g. all fields are made optional, and non-expected fields are added as dict attributes). """
@classmethod def parse_obj_as_list(cls: type[T], data: bytes | str | list | dict) -> list[T]: """Alias to parse server response and return a single instance.
See `parse_obj` for more details. """ output = cls.parse_obj(data) if not isinstance(output, list): raise ValueError(f"Invalid input data for {cls}. Expected a list, but got {type(output)}.") return output
@classmethod def parse_obj_as_instance(cls: type[T], data: bytes | str | list | dict) -> T: """Alias to parse server response and return a single instance.
See `parse_obj` for more details. """ output = cls.parse_obj(data) if isinstance(output, list): raise ValueError(f"Invalid input data for {cls}. Expected a single instance, but got a list.") return output
@classmethod def parse_obj(cls: type[T], data: bytes | str | list | dict) -> list[T] | T: """Parse server response as a dataclass or list of dataclasses.
To enable future-compatibility, we want to handle cases where the server return more fields than expected. In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are added as dict attributes. """ # Parse server response (from bytes) if isinstance(data, bytes): data = data.decode() if isinstance(data, str): data = json.loads(data)
# If a list, parse each item individually if isinstance(data, list): return [cls.parse_obj(d) for d in data] # type: ignore
# At this point, we expect a dict if not isinstance(data, dict): raise ValueError(f"Invalid data type: {type(data)}")
init_values = {} other_values = {} for key, value in data.items(): key = normalize_key(key) if key in cls.__dataclass_fields__ and cls.__dataclass_fields__[key].init: if isinstance(value, dict) or isinstance(value, list): field_type = cls.__dataclass_fields__[key].type
# if `field_type` is a `BaseInferenceType`, parse it if inspect.isclass(field_type) and issubclass(field_type, BaseInferenceType): value = field_type.parse_obj(value)
# otherwise, recursively parse nested dataclasses (if possible) # `get_args` returns handle Union and Optional for us else: expected_types = get_args(field_type) for expected_type in expected_types: if ( isinstance(expected_type, types.GenericAlias) and expected_type.__origin__ is list ) or getattr(expected_type, "_name", None) == "List": expected_type = get_args(expected_type)[ 0 ] # assume same type for all items in the list if inspect.isclass(expected_type) and issubclass(expected_type, BaseInferenceType): value = expected_type.parse_obj(value) break init_values[key] = value else: other_values[key] = value
# Make all missing fields default to None # => ensure that dataclass initialization will never fail even if the server does not return all fields. for key in cls.__dataclass_fields__: if key not in init_values: init_values[key] = None
# Initialize dataclass with expected values item = cls(**init_values)
# Add remaining fields as dict attributes item.update(other_values)
# Add remaining fields as extra dataclass fields. # They won't be part of the dataclass fields but will be accessible as attributes. # Use @dataclass_with_extra to show them in __repr__. item.__dict__.update(other_values) return item
def __post_init__(self): self.update(asdict(self))
def __setitem__(self, __key: Any, __value: Any) -> None: # Hacky way to keep dataclass values in sync when dict is updated super().__setitem__(__key, __value) if __key in self.__dataclass_fields__ and getattr(self, __key, None) != __value: self.__setattr__(__key, __value) return
def __setattr__(self, __name: str, __value: Any) -> None: # Hacky way to keep dict values is sync when dataclass is updated super().__setattr__(__name, __value) if self.get(__name) != __value: self[__name] = __value return
def normalize_key(key: str) -> str: # e.g "content-type" -> "content_type", "Accept" -> "accept" return key.replace("-", "_").replace(" ", "_").lower()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any, Literal, Union
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass ChatCompletionInputURL(BaseInferenceType): url: str
ChatCompletionInputMessageChunkType = Literal["text", "image_url"]
@dataclass_with_extraclass ChatCompletionInputMessageChunk(BaseInferenceType): type: "ChatCompletionInputMessageChunkType" image_url: ChatCompletionInputURL | None = None text: str | None = None
@dataclass_with_extraclass ChatCompletionInputFunctionDefinition(BaseInferenceType): name: str parameters: Any description: str | None = None
@dataclass_with_extraclass ChatCompletionInputToolCall(BaseInferenceType): function: ChatCompletionInputFunctionDefinition id: str type: str
@dataclass_with_extraclass ChatCompletionInputMessage(BaseInferenceType): role: str content: list[ChatCompletionInputMessageChunk] | str | None = None name: str | None = None tool_calls: list[ChatCompletionInputToolCall] | None = None
@dataclass_with_extraclass ChatCompletionInputJSONSchema(BaseInferenceType): name: str """ The name of the response format. """ description: str | None = None """ A description of what the response format is for, used by the model to determine how to respond in the format. """ schema: dict[str, object] | None = None """ The schema for the response format, described as a JSON Schema object. Learn how to build JSON schemas [here](https://json-schema.org/). """ strict: bool | None = None """ Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. """
@dataclass_with_extraclass ChatCompletionInputResponseFormatText(BaseInferenceType): type: Literal["text"]
@dataclass_with_extraclass ChatCompletionInputResponseFormatJSONSchema(BaseInferenceType): type: Literal["json_schema"] json_schema: ChatCompletionInputJSONSchema
@dataclass_with_extraclass ChatCompletionInputResponseFormatJSONObject(BaseInferenceType): type: Literal["json_object"]
ChatCompletionInputGrammarType = Union[ ChatCompletionInputResponseFormatText, ChatCompletionInputResponseFormatJSONSchema, ChatCompletionInputResponseFormatJSONObject,]
@dataclass_with_extraclass ChatCompletionInputStreamOptions(BaseInferenceType): include_usage: bool | None = None """If set, an additional chunk will be streamed before the data: [DONE] message. The usage field on this chunk shows the token usage statistics for the entire request, and the choices field will always be an empty array. All other chunks will also include a usage field, but with a null value. """
@dataclass_with_extraclass ChatCompletionInputFunctionName(BaseInferenceType): name: str
@dataclass_with_extraclass ChatCompletionInputToolChoiceClass(BaseInferenceType): function: ChatCompletionInputFunctionName
ChatCompletionInputToolChoiceEnum = Literal["auto", "none", "required"]
@dataclass_with_extraclass ChatCompletionInputTool(BaseInferenceType): function: ChatCompletionInputFunctionDefinition type: str
@dataclass_with_extraclass ChatCompletionInput(BaseInferenceType): """Chat Completion Input. Auto-generated from TGI specs. For more details, check out https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts. """
messages: list[ChatCompletionInputMessage] """A list of messages comprising the conversation so far.""" frequency_penalty: float | None = None """Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. """ logit_bias: list[float] | None = None """UNUSED Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. """ logprobs: bool | None = None """Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message. """ max_tokens: int | None = None """The maximum number of tokens that can be generated in the chat completion.""" model: str | None = None """[UNUSED] ID of the model to use. See the model endpoint compatibility table for details on which models work with the Chat API. """ n: int | None = None """UNUSED How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep n as 1 to minimize costs. """ presence_penalty: float | None = None """Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics """ response_format: ChatCompletionInputGrammarType | None = None seed: int | None = None stop: list[str] | None = None """Up to 4 sequences where the API will stop generating further tokens.""" stream: bool | None = None stream_options: ChatCompletionInputStreamOptions | None = None temperature: float | None = None """What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both. """ tool_choice: Union[ChatCompletionInputToolChoiceClass, "ChatCompletionInputToolChoiceEnum"] | None = None tool_prompt: str | None = None """A prompt to be appended before the tools""" tools: list[ChatCompletionInputTool] | None = None """A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. """ top_logprobs: int | None = None """An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. logprobs must be set to true if this parameter is used. """ top_p: float | None = None """An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. """
@dataclass_with_extraclass ChatCompletionOutputTopLogprob(BaseInferenceType): logprob: float token: str
@dataclass_with_extraclass ChatCompletionOutputLogprob(BaseInferenceType): logprob: float token: str top_logprobs: list[ChatCompletionOutputTopLogprob]
@dataclass_with_extraclass ChatCompletionOutputLogprobs(BaseInferenceType): content: list[ChatCompletionOutputLogprob]
@dataclass_with_extraclass ChatCompletionOutputFunctionDefinition(BaseInferenceType): arguments: str name: str description: str | None = None
@dataclass_with_extraclass ChatCompletionOutputToolCall(BaseInferenceType): function: ChatCompletionOutputFunctionDefinition id: str type: str
@dataclass_with_extraclass ChatCompletionOutputMessage(BaseInferenceType): role: str content: str | None = None reasoning: str | None = None tool_call_id: str | None = None tool_calls: list[ChatCompletionOutputToolCall] | None = None
@dataclass_with_extraclass ChatCompletionOutputComplete(BaseInferenceType): finish_reason: str index: int message: ChatCompletionOutputMessage logprobs: ChatCompletionOutputLogprobs | None = None
@dataclass_with_extraclass ChatCompletionOutputUsage(BaseInferenceType): completion_tokens: int prompt_tokens: int total_tokens: int
@dataclass_with_extraclass ChatCompletionOutput(BaseInferenceType): """Chat Completion Output. Auto-generated from TGI specs. For more details, check out https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts. """
choices: list[ChatCompletionOutputComplete] created: int id: str model: str system_fingerprint: str usage: ChatCompletionOutputUsage
@dataclass_with_extraclass ChatCompletionStreamOutputFunction(BaseInferenceType): arguments: str name: str | None = None
@dataclass_with_extraclass ChatCompletionStreamOutputDeltaToolCall(BaseInferenceType): function: ChatCompletionStreamOutputFunction id: str index: int type: str
@dataclass_with_extraclass ChatCompletionStreamOutputDelta(BaseInferenceType): role: str content: str | None = None reasoning: str | None = None tool_call_id: str | None = None tool_calls: list[ChatCompletionStreamOutputDeltaToolCall] | None = None
@dataclass_with_extraclass ChatCompletionStreamOutputTopLogprob(BaseInferenceType): logprob: float token: str
@dataclass_with_extraclass ChatCompletionStreamOutputLogprob(BaseInferenceType): logprob: float token: str top_logprobs: list[ChatCompletionStreamOutputTopLogprob]
@dataclass_with_extraclass ChatCompletionStreamOutputLogprobs(BaseInferenceType): content: list[ChatCompletionStreamOutputLogprob]
@dataclass_with_extraclass ChatCompletionStreamOutputChoice(BaseInferenceType): delta: ChatCompletionStreamOutputDelta index: int finish_reason: str | None = None logprobs: ChatCompletionStreamOutputLogprobs | None = None
@dataclass_with_extraclass ChatCompletionStreamOutputUsage(BaseInferenceType): completion_tokens: int prompt_tokens: int total_tokens: int
@dataclass_with_extraclass ChatCompletionStreamOutput(BaseInferenceType): """Chat Completion Stream Output. Auto-generated from TGI specs. For more details, check out https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts. """
choices: list[ChatCompletionStreamOutputChoice] created: int id: str model: str system_fingerprint: str usage: ChatCompletionStreamOutputUsage | None = None12345678910111213141516171819202122232425262728# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass DepthEstimationInput(BaseInferenceType): """Inputs for Depth Estimation inference"""
inputs: Any """The input image data""" parameters: dict[str, Any] | None = None """Additional inference parameters for Depth Estimation"""
@dataclass_with_extraclass DepthEstimationOutput(BaseInferenceType): """Outputs of inference for the Depth Estimation task"""
depth: Any """The predicted depth as an image""" predicted_depth: Any """The predicted depth as a tensor"""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass DocumentQuestionAnsweringInputData(BaseInferenceType): """One (document, question) pair to answer"""
image: Any """The image on which the question is asked""" question: str """A question to ask of the document"""
@dataclass_with_extraclass DocumentQuestionAnsweringParameters(BaseInferenceType): """Additional inference parameters for Document Question Answering"""
doc_stride: int | None = None """If the words in the document are too long to fit with the question for the model, it will be split in several chunks with some overlap. This argument controls the size of that overlap. """ handle_impossible_answer: bool | None = None """Whether to accept impossible as an answer""" lang: str | None = None """Language to use while running OCR. Defaults to english.""" max_answer_len: int | None = None """The maximum length of predicted answers (e.g., only answers with a shorter length are considered). """ max_question_len: int | None = None """The maximum length of the question after tokenization. It will be truncated if needed.""" max_seq_len: int | None = None """The maximum length of the total sentence (context + question) in tokens of each chunk passed to the model. The context will be split in several chunks (using doc_stride as overlap) if needed. """ top_k: int | None = None """The number of answers to return (will be chosen by order of likelihood). Can return less than top_k answers if there are not enough options available within the context. """ word_boxes: list[list[float] | str] | None = None """A list of words and bounding boxes (normalized 0->1000). If provided, the inference will skip the OCR step and use the provided bounding boxes instead. """
@dataclass_with_extraclass DocumentQuestionAnsweringInput(BaseInferenceType): """Inputs for Document Question Answering inference"""
inputs: DocumentQuestionAnsweringInputData """One (document, question) pair to answer""" parameters: DocumentQuestionAnsweringParameters | None = None """Additional inference parameters for Document Question Answering"""
@dataclass_with_extraclass DocumentQuestionAnsweringOutputElement(BaseInferenceType): """Outputs of inference for the Document Question Answering task"""
answer: str """The answer to the question.""" end: int """The end word index of the answer (in the OCR’d version of the input or provided word boxes). """ score: float """The probability associated to the answer.""" start: int """The start word index of the answer (in the OCR’d version of the input or provided word boxes). """123456789101112131415161718192021222324252627282930313233343536# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Literal, Optional
from .base import BaseInferenceType, dataclass_with_extra
FeatureExtractionInputTruncationDirection = Literal["left", "right"]
@dataclass_with_extraclass FeatureExtractionInput(BaseInferenceType): """Feature Extraction Input. Auto-generated from TEI specs. For more details, check out https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tei-import.ts. """
inputs: list[str] | str """The text or list of texts to embed.""" normalize: bool | None = None prompt_name: str | None = None """The name of the prompt that should be used by for encoding. If not set, no prompt will be applied. Must be a key in the `sentence-transformers` configuration `prompts` dictionary. For example if ``prompt_name`` is "query" and the ``prompts`` is {"query": "query: ", ...}, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?" because the prompt text will be prepended before any text to encode. """ truncate: bool | None = None truncation_direction: Optional["FeatureExtractionInputTruncationDirection"] = None1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass FillMaskParameters(BaseInferenceType): """Additional inference parameters for Fill Mask"""
targets: list[str] | None = None """When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocabulary. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). """ top_k: int | None = None """When passed, overrides the number of predictions to return."""
@dataclass_with_extraclass FillMaskInput(BaseInferenceType): """Inputs for Fill Mask inference"""
inputs: str """The text with masked tokens""" parameters: FillMaskParameters | None = None """Additional inference parameters for Fill Mask"""
@dataclass_with_extraclass FillMaskOutputElement(BaseInferenceType): """Outputs of inference for the Fill Mask task"""
score: float """The corresponding probability""" sequence: str """The corresponding input with the mask token prediction.""" token: int """The predicted token id (to replace the masked one).""" token_str: Any fill_mask_output_token_str: str | None = None """The predicted token (to replace the masked one)."""12345678910111213141516171819202122232425262728293031323334353637383940414243# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Literal, Optional
from .base import BaseInferenceType, dataclass_with_extra
ImageClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
@dataclass_with_extraclass ImageClassificationParameters(BaseInferenceType): """Additional inference parameters for Image Classification"""
function_to_apply: Optional["ImageClassificationOutputTransform"] = None """The function to apply to the model outputs in order to retrieve the scores.""" top_k: int | None = None """When specified, limits the output to the top K most probable classes."""
@dataclass_with_extraclass ImageClassificationInput(BaseInferenceType): """Inputs for Image Classification inference"""
inputs: str """The input image data as a base64-encoded string. If no `parameters` are provided, you can also provide the image data as a raw bytes payload. """ parameters: ImageClassificationParameters | None = None """Additional inference parameters for Image Classification"""
@dataclass_with_extraclass ImageClassificationOutputElement(BaseInferenceType): """Outputs of inference for the Image Classification task"""
label: str """The predicted class label.""" score: float """The corresponding probability."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Literal, Optional
from .base import BaseInferenceType, dataclass_with_extra
ImageSegmentationSubtask = Literal["instance", "panoptic", "semantic"]
@dataclass_with_extraclass ImageSegmentationParameters(BaseInferenceType): """Additional inference parameters for Image Segmentation"""
mask_threshold: float | None = None """Threshold to use when turning the predicted masks into binary values.""" overlap_mask_area_threshold: float | None = None """Mask overlap threshold to eliminate small, disconnected segments.""" subtask: Optional["ImageSegmentationSubtask"] = None """Segmentation task to be performed, depending on model capabilities.""" threshold: float | None = None """Probability threshold to filter out predicted masks."""
@dataclass_with_extraclass ImageSegmentationInput(BaseInferenceType): """Inputs for Image Segmentation inference"""
inputs: str """The input image data as a base64-encoded string. If no `parameters` are provided, you can also provide the image data as a raw bytes payload. """ parameters: ImageSegmentationParameters | None = None """Additional inference parameters for Image Segmentation"""
@dataclass_with_extraclass ImageSegmentationOutputElement(BaseInferenceType): """Outputs of inference for the Image Segmentation task A predicted mask / segment """
label: str """The label of the predicted segment.""" mask: str """The corresponding mask as a black-and-white image (base64-encoded).""" score: float | None = None """The score or confidence degree the model has."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass ImageTextToImageTargetSize(BaseInferenceType): """The size in pixels of the output image. This parameter is only supported by some providers and for specific models. It will be ignored when unsupported. """
height: int width: int
@dataclass_with_extraclass ImageTextToImageParameters(BaseInferenceType): """Additional inference parameters for Image Text To Image"""
guidance_scale: float | None = None """For diffusion models. A higher guidance scale value encourages the model to generate images closely linked to the text prompt at the expense of lower image quality. """ negative_prompt: str | None = None """One prompt to guide what NOT to include in image generation.""" num_inference_steps: int | None = None """For diffusion models. The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference. """ prompt: str | None = None """The text prompt to guide the image generation. Either this or inputs (image) must be provided. """ seed: int | None = None """Seed for the random number generator.""" target_size: ImageTextToImageTargetSize | None = None """The size in pixels of the output image. This parameter is only supported by some providers and for specific models. It will be ignored when unsupported. """
@dataclass_with_extraclass ImageTextToImageInput(BaseInferenceType): """Inputs for Image Text To Image inference. Either inputs (image) or prompt (in parameters) must be provided, or both. """
inputs: str | None = None """The input image data as a base64-encoded string. If no `parameters` are provided, you can also provide the image data as a raw bytes payload. Either this or prompt must be provided. """ parameters: ImageTextToImageParameters | None = None """Additional inference parameters for Image Text To Image"""
@dataclass_with_extraclass ImageTextToImageOutput(BaseInferenceType): """Outputs of inference for the Image Text To Image task"""
image: Any """The generated image returned as raw bytes in the payload."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass ImageTextToVideoTargetSize(BaseInferenceType): """The size in pixel of the output video frames."""
height: int width: int
@dataclass_with_extraclass ImageTextToVideoParameters(BaseInferenceType): """Additional inference parameters for Image Text To Video"""
guidance_scale: float | None = None """For diffusion models. A higher guidance scale value encourages the model to generate videos closely linked to the text prompt at the expense of lower image quality. """ negative_prompt: str | None = None """One prompt to guide what NOT to include in video generation.""" num_frames: float | None = None """The num_frames parameter determines how many video frames are generated.""" num_inference_steps: int | None = None """The number of denoising steps. More denoising steps usually lead to a higher quality video at the expense of slower inference. """ prompt: str | None = None """The text prompt to guide the video generation. Either this or inputs (image) must be provided. """ seed: int | None = None """Seed for the random number generator.""" target_size: ImageTextToVideoTargetSize | None = None """The size in pixel of the output video frames."""
@dataclass_with_extraclass ImageTextToVideoInput(BaseInferenceType): """Inputs for Image Text To Video inference. Either inputs (image) or prompt (in parameters) must be provided, or both. """
inputs: str | None = None """The input image data as a base64-encoded string. If no `parameters` are provided, you can also provide the image data as a raw bytes payload. Either this or prompt must be provided. """ parameters: ImageTextToVideoParameters | None = None """Additional inference parameters for Image Text To Video"""
@dataclass_with_extraclass ImageTextToVideoOutput(BaseInferenceType): """Outputs of inference for the Image Text To Video task"""
video: Any """The generated video returned as raw bytes in the payload."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass ImageToImageTargetSize(BaseInferenceType): """The size in pixels of the output image. This parameter is only supported by some providers and for specific models. It will be ignored when unsupported. """
height: int width: int
@dataclass_with_extraclass ImageToImageParameters(BaseInferenceType): """Additional inference parameters for Image To Image"""
guidance_scale: float | None = None """For diffusion models. A higher guidance scale value encourages the model to generate images closely linked to the text prompt at the expense of lower image quality. """ negative_prompt: str | None = None """One prompt to guide what NOT to include in image generation.""" num_inference_steps: int | None = None """For diffusion models. The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference. """ prompt: str | None = None """The text prompt to guide the image generation.""" target_size: ImageToImageTargetSize | None = None """The size in pixels of the output image. This parameter is only supported by some providers and for specific models. It will be ignored when unsupported. """
@dataclass_with_extraclass ImageToImageInput(BaseInferenceType): """Inputs for Image To Image inference"""
inputs: str """The input image data as a base64-encoded string. If no `parameters` are provided, you can also provide the image data as a raw bytes payload. """ parameters: ImageToImageParameters | None = None """Additional inference parameters for Image To Image"""
@dataclass_with_extraclass ImageToImageOutput(BaseInferenceType): """Outputs of inference for the Image To Image task"""
image: Any """The output image returned as raw bytes in the payload."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any, Literal, Union
from .base import BaseInferenceType, dataclass_with_extra
ImageToTextEarlyStoppingEnum = Literal["never"]
@dataclass_with_extraclass ImageToTextGenerationParameters(BaseInferenceType): """Parametrization of the text generation process"""
do_sample: bool | None = None """Whether to use sampling instead of greedy decoding when generating new tokens.""" early_stopping: Union[bool, "ImageToTextEarlyStoppingEnum"] | None = None """Controls the stopping condition for beam-based methods.""" epsilon_cutoff: float | None = None """If set to float strictly between 0 and 1, only tokens with a conditional probability greater than epsilon_cutoff will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) for more details. """ eta_cutoff: float | None = None """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) for more details. """ max_length: int | None = None """The maximum length (in tokens) of the generated text, including the input.""" max_new_tokens: int | None = None """The maximum number of tokens to generate. Takes precedence over max_length.""" min_length: int | None = None """The minimum length (in tokens) of the generated text, including the input.""" min_new_tokens: int | None = None """The minimum number of tokens to generate. Takes precedence over min_length.""" num_beam_groups: int | None = None """Number of groups to divide num_beams into in order to ensure diversity among different groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details. """ num_beams: int | None = None """Number of beams to use for beam search.""" penalty_alpha: float | None = None """The value balances the model confidence and the degeneration penalty in contrastive search decoding. """ temperature: float | None = None """The value used to modulate the next token probabilities.""" top_k: int | None = None """The number of highest probability vocabulary tokens to keep for top-k-filtering.""" top_p: float | None = None """If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. """ typical_p: float | None = None """Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to typical_p or higher are kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details. """ use_cache: bool | None = None """Whether the model should use the past last key/values attentions to speed up decoding"""
@dataclass_with_extraclass ImageToTextParameters(BaseInferenceType): """Additional inference parameters for Image To Text"""
generation_parameters: ImageToTextGenerationParameters | None = None """Parametrization of the text generation process""" max_new_tokens: int | None = None """The amount of maximum tokens to generate."""
@dataclass_with_extraclass ImageToTextInput(BaseInferenceType): """Inputs for Image To Text inference"""
inputs: Any """The input image data""" parameters: ImageToTextParameters | None = None """Additional inference parameters for Image To Text"""
@dataclass_with_extraclass ImageToTextOutput(BaseInferenceType): """Outputs of inference for the Image To Text task"""
generated_text: Any image_to_text_output_generated_text: str | None = None """The generated text."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass ImageToVideoTargetSize(BaseInferenceType): """The size in pixel of the output video frames."""
height: int width: int
@dataclass_with_extraclass ImageToVideoParameters(BaseInferenceType): """Additional inference parameters for Image To Video"""
guidance_scale: float | None = None """For diffusion models. A higher guidance scale value encourages the model to generate videos closely linked to the text prompt at the expense of lower image quality. """ negative_prompt: str | None = None """One prompt to guide what NOT to include in video generation.""" num_frames: float | None = None """The num_frames parameter determines how many video frames are generated.""" num_inference_steps: int | None = None """The number of denoising steps. More denoising steps usually lead to a higher quality video at the expense of slower inference. """ prompt: str | None = None """The text prompt to guide the video generation.""" seed: int | None = None """Seed for the random number generator.""" target_size: ImageToVideoTargetSize | None = None """The size in pixel of the output video frames."""
@dataclass_with_extraclass ImageToVideoInput(BaseInferenceType): """Inputs for Image To Video inference"""
inputs: str """The input image data as a base64-encoded string. If no `parameters` are provided, you can also provide the image data as a raw bytes payload. """ parameters: ImageToVideoParameters | None = None """Additional inference parameters for Image To Video"""
@dataclass_with_extraclass ImageToVideoOutput(BaseInferenceType): """Outputs of inference for the Image To Video task"""
video: Any """The generated video returned as raw bytes in the payload."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass ObjectDetectionParameters(BaseInferenceType): """Additional inference parameters for Object Detection"""
threshold: float | None = None """The probability necessary to make a prediction."""
@dataclass_with_extraclass ObjectDetectionInput(BaseInferenceType): """Inputs for Object Detection inference"""
inputs: str """The input image data as a base64-encoded string. If no `parameters` are provided, you can also provide the image data as a raw bytes payload. """ parameters: ObjectDetectionParameters | None = None """Additional inference parameters for Object Detection"""
@dataclass_with_extraclass ObjectDetectionBoundingBox(BaseInferenceType): """The predicted bounding box. Coordinates are relative to the top left corner of the input image. """
xmax: int """The x-coordinate of the bottom-right corner of the bounding box.""" xmin: int """The x-coordinate of the top-left corner of the bounding box.""" ymax: int """The y-coordinate of the bottom-right corner of the bounding box.""" ymin: int """The y-coordinate of the top-left corner of the bounding box."""
@dataclass_with_extraclass ObjectDetectionOutputElement(BaseInferenceType): """Outputs of inference for the Object Detection task"""
box: ObjectDetectionBoundingBox """The predicted bounding box. Coordinates are relative to the top left corner of the input image. """ label: str """The predicted label for the bounding box.""" score: float """The associated score / probability."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass QuestionAnsweringInputData(BaseInferenceType): """One (context, question) pair to answer"""
context: str """The context to be used for answering the question""" question: str """The question to be answered"""
@dataclass_with_extraclass QuestionAnsweringParameters(BaseInferenceType): """Additional inference parameters for Question Answering"""
align_to_words: bool | None = None """Attempts to align the answer to real words. Improves quality on space separated languages. Might hurt on non-space-separated languages (like Japanese or Chinese) """ doc_stride: int | None = None """If the context is too long to fit with the question for the model, it will be split in several chunks with some overlap. This argument controls the size of that overlap. """ handle_impossible_answer: bool | None = None """Whether to accept impossible as an answer.""" max_answer_len: int | None = None """The maximum length of predicted answers (e.g., only answers with a shorter length are considered). """ max_question_len: int | None = None """The maximum length of the question after tokenization. It will be truncated if needed.""" max_seq_len: int | None = None """The maximum length of the total sentence (context + question) in tokens of each chunk passed to the model. The context will be split in several chunks (using docStride as overlap) if needed. """ top_k: int | None = None """The number of answers to return (will be chosen by order of likelihood). Note that we return less than topk answers if there are not enough options available within the context. """
@dataclass_with_extraclass QuestionAnsweringInput(BaseInferenceType): """Inputs for Question Answering inference"""
inputs: QuestionAnsweringInputData """One (context, question) pair to answer""" parameters: QuestionAnsweringParameters | None = None """Additional inference parameters for Question Answering"""
@dataclass_with_extraclass QuestionAnsweringOutputElement(BaseInferenceType): """Outputs of inference for the Question Answering task"""
answer: str """The answer to the question.""" end: int """The character position in the input where the answer ends.""" score: float """The probability associated to the answer.""" start: int """The character position in the input where the answer begins."""123456789101112131415161718192021222324252627# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass SentenceSimilarityInputData(BaseInferenceType): sentences: list[str] """A list of strings which will be compared against the source_sentence.""" source_sentence: str """The string that you wish to compare the other strings with. This can be a phrase, sentence, or longer passage, depending on the model being used. """
@dataclass_with_extraclass SentenceSimilarityInput(BaseInferenceType): """Inputs for Sentence similarity inference"""
inputs: SentenceSimilarityInputData parameters: dict[str, Any] | None = None """Additional inference parameters for Sentence Similarity"""1234567891011121314151617181920212223242526272829303132333435363738394041# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any, Literal, Optional
from .base import BaseInferenceType, dataclass_with_extra
SummarizationTruncationStrategy = Literal["do_not_truncate", "longest_first", "only_first", "only_second"]
@dataclass_with_extraclass SummarizationParameters(BaseInferenceType): """Additional inference parameters for summarization."""
clean_up_tokenization_spaces: bool | None = None """Whether to clean up the potential extra spaces in the text output.""" generate_parameters: dict[str, Any] | None = None """Additional parametrization of the text generation algorithm.""" truncation: Optional["SummarizationTruncationStrategy"] = None """The truncation strategy to use."""
@dataclass_with_extraclass SummarizationInput(BaseInferenceType): """Inputs for Summarization inference"""
inputs: str """The input text to summarize.""" parameters: SummarizationParameters | None = None """Additional inference parameters for summarization."""
@dataclass_with_extraclass SummarizationOutput(BaseInferenceType): """Outputs of inference for the Summarization task"""
summary_text: str """The summarized text."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Literal, Optional
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass TableQuestionAnsweringInputData(BaseInferenceType): """One (table, question) pair to answer"""
question: str """The question to be answered about the table""" table: dict[str, list[str]] """The table to serve as context for the questions"""
Padding = Literal["do_not_pad", "longest", "max_length"]
@dataclass_with_extraclass TableQuestionAnsweringParameters(BaseInferenceType): """Additional inference parameters for Table Question Answering"""
padding: Optional["Padding"] = None """Activates and controls padding.""" sequential: bool | None = None """Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the inference to be done sequentially to extract relations within sequences, given their conversational nature. """ truncation: bool | None = None """Activates and controls truncation."""
@dataclass_with_extraclass TableQuestionAnsweringInput(BaseInferenceType): """Inputs for Table Question Answering inference"""
inputs: TableQuestionAnsweringInputData """One (table, question) pair to answer""" parameters: TableQuestionAnsweringParameters | None = None """Additional inference parameters for Table Question Answering"""
@dataclass_with_extraclass TableQuestionAnsweringOutputElement(BaseInferenceType): """Outputs of inference for the Table Question Answering task"""
answer: str """The answer of the question given the table. If there is an aggregator, the answer will be preceded by `AGGREGATOR >`. """ cells: list[str] """list of strings made up of the answer cell values.""" coordinates: list[list[int]] """Coordinates of the cells of the answers.""" aggregator: str | None = None """If the model has an aggregator, this returns the aggregator."""123456789101112131415161718192021222324252627282930313233343536373839404142# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any, Literal, Optional
from .base import BaseInferenceType, dataclass_with_extra
Text2TextGenerationTruncationStrategy = Literal["do_not_truncate", "longest_first", "only_first", "only_second"]
@dataclass_with_extraclass Text2TextGenerationParameters(BaseInferenceType): """Additional inference parameters for Text2text Generation"""
clean_up_tokenization_spaces: bool | None = None """Whether to clean up the potential extra spaces in the text output.""" generate_parameters: dict[str, Any] | None = None """Additional parametrization of the text generation algorithm""" truncation: Optional["Text2TextGenerationTruncationStrategy"] = None """The truncation strategy to use"""
@dataclass_with_extraclass Text2TextGenerationInput(BaseInferenceType): """Inputs for Text2text Generation inference"""
inputs: str """The input text data""" parameters: Text2TextGenerationParameters | None = None """Additional inference parameters for Text2text Generation"""
@dataclass_with_extraclass Text2TextGenerationOutput(BaseInferenceType): """Outputs of inference for the Text2text Generation task"""
generated_text: Any text2_text_generation_output_generated_text: str | None = None """The generated text."""1234567891011121314151617181920212223242526272829303132333435363738394041# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Literal, Optional
from .base import BaseInferenceType, dataclass_with_extra
TextClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
@dataclass_with_extraclass TextClassificationParameters(BaseInferenceType): """Additional inference parameters for Text Classification"""
function_to_apply: Optional["TextClassificationOutputTransform"] = None """The function to apply to the model outputs in order to retrieve the scores.""" top_k: int | None = None """When specified, limits the output to the top K most probable classes."""
@dataclass_with_extraclass TextClassificationInput(BaseInferenceType): """Inputs for Text Classification inference"""
inputs: str """The text to classify""" parameters: TextClassificationParameters | None = None """Additional inference parameters for Text Classification"""
@dataclass_with_extraclass TextClassificationOutputElement(BaseInferenceType): """Outputs of inference for the Text Classification task"""
label: str """The predicted class label.""" score: float """The corresponding probability."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any, Literal
from .base import BaseInferenceType, dataclass_with_extra
TypeEnum = Literal["json", "regex", "json_schema"]
@dataclass_with_extraclass TextGenerationInputGrammarType(BaseInferenceType): type: "TypeEnum" value: Any """A string that represents a [JSON Schema](https://json-schema.org/). JSON Schema is a declarative language that allows to annotate JSON documents with types and descriptions. """
@dataclass_with_extraclass TextGenerationInputGenerateParameters(BaseInferenceType): adapter_id: str | None = None """Lora adapter id""" best_of: int | None = None """Generate best_of sequences and return the one if the highest token logprobs.""" decoder_input_details: bool | None = None """Whether to return decoder input token logprobs and ids.""" details: bool | None = None """Whether to return generation details.""" do_sample: bool | None = None """Activate logits sampling.""" frequency_penalty: float | None = None """The parameter for frequency penalty. 1.0 means no penalty Penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. """ grammar: TextGenerationInputGrammarType | None = None max_new_tokens: int | None = None """Maximum number of tokens to generate.""" repetition_penalty: float | None = None """The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details. """ return_full_text: bool | None = None """Whether to prepend the prompt to the generated text""" seed: int | None = None """Random sampling seed.""" stop: list[str] | None = None """Stop generating tokens if a member of `stop` is generated.""" temperature: float | None = None """The value used to module the logits distribution.""" top_k: int | None = None """The number of highest probability vocabulary tokens to keep for top-k-filtering.""" top_n_tokens: int | None = None """The number of highest probability vocabulary tokens to keep for top-n-filtering.""" top_p: float | None = None """Top-p value for nucleus sampling.""" truncate: int | None = None """Truncate inputs tokens to the given size.""" typical_p: float | None = None """Typical Decoding mass See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information. """ watermark: bool | None = None """Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226). """
@dataclass_with_extraclass TextGenerationInput(BaseInferenceType): """Text Generation Input. Auto-generated from TGI specs. For more details, check out https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts. """
inputs: str parameters: TextGenerationInputGenerateParameters | None = None stream: bool | None = None
TextGenerationOutputFinishReason = Literal["length", "eos_token", "stop_sequence"]
@dataclass_with_extraclass TextGenerationOutputPrefillToken(BaseInferenceType): id: int logprob: float text: str
@dataclass_with_extraclass TextGenerationOutputToken(BaseInferenceType): id: int logprob: float special: bool text: str
@dataclass_with_extraclass TextGenerationOutputBestOfSequence(BaseInferenceType): finish_reason: "TextGenerationOutputFinishReason" generated_text: str generated_tokens: int prefill: list[TextGenerationOutputPrefillToken] tokens: list[TextGenerationOutputToken] seed: int | None = None top_tokens: list[list[TextGenerationOutputToken]] | None = None
@dataclass_with_extraclass TextGenerationOutputDetails(BaseInferenceType): finish_reason: "TextGenerationOutputFinishReason" generated_tokens: int prefill: list[TextGenerationOutputPrefillToken] tokens: list[TextGenerationOutputToken] best_of_sequences: list[TextGenerationOutputBestOfSequence] | None = None seed: int | None = None top_tokens: list[list[TextGenerationOutputToken]] | None = None
@dataclass_with_extraclass TextGenerationOutput(BaseInferenceType): """Text Generation Output. Auto-generated from TGI specs. For more details, check out https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts. """
generated_text: str details: TextGenerationOutputDetails | None = None
@dataclass_with_extraclass TextGenerationStreamOutputStreamDetails(BaseInferenceType): finish_reason: "TextGenerationOutputFinishReason" generated_tokens: int input_length: int seed: int | None = None
@dataclass_with_extraclass TextGenerationStreamOutputToken(BaseInferenceType): id: int logprob: float special: bool text: str
@dataclass_with_extraclass TextGenerationStreamOutput(BaseInferenceType): """Text Generation Stream Output. Auto-generated from TGI specs. For more details, check out https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts. """
index: int token: TextGenerationStreamOutputToken details: TextGenerationStreamOutputStreamDetails | None = None generated_text: str | None = None top_tokens: list[TextGenerationStreamOutputToken] | None = None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any, Literal, Union
from .base import BaseInferenceType, dataclass_with_extra
TextToAudioEarlyStoppingEnum = Literal["never"]
@dataclass_with_extraclass TextToAudioGenerationParameters(BaseInferenceType): """Parametrization of the text generation process"""
do_sample: bool | None = None """Whether to use sampling instead of greedy decoding when generating new tokens.""" early_stopping: Union[bool, "TextToAudioEarlyStoppingEnum"] | None = None """Controls the stopping condition for beam-based methods.""" epsilon_cutoff: float | None = None """If set to float strictly between 0 and 1, only tokens with a conditional probability greater than epsilon_cutoff will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) for more details. """ eta_cutoff: float | None = None """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) for more details. """ max_length: int | None = None """The maximum length (in tokens) of the generated text, including the input.""" max_new_tokens: int | None = None """The maximum number of tokens to generate. Takes precedence over max_length.""" min_length: int | None = None """The minimum length (in tokens) of the generated text, including the input.""" min_new_tokens: int | None = None """The minimum number of tokens to generate. Takes precedence over min_length.""" num_beam_groups: int | None = None """Number of groups to divide num_beams into in order to ensure diversity among different groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details. """ num_beams: int | None = None """Number of beams to use for beam search.""" penalty_alpha: float | None = None """The value balances the model confidence and the degeneration penalty in contrastive search decoding. """ temperature: float | None = None """The value used to modulate the next token probabilities.""" top_k: int | None = None """The number of highest probability vocabulary tokens to keep for top-k-filtering.""" top_p: float | None = None """If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. """ typical_p: float | None = None """Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to typical_p or higher are kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details. """ use_cache: bool | None = None """Whether the model should use the past last key/values attentions to speed up decoding"""
@dataclass_with_extraclass TextToAudioParameters(BaseInferenceType): """Additional inference parameters for Text To Audio"""
generation_parameters: TextToAudioGenerationParameters | None = None """Parametrization of the text generation process"""
@dataclass_with_extraclass TextToAudioInput(BaseInferenceType): """Inputs for Text To Audio inference"""
inputs: str """The input text data""" parameters: TextToAudioParameters | None = None """Additional inference parameters for Text To Audio"""
@dataclass_with_extraclass TextToAudioOutput(BaseInferenceType): """Outputs of inference for the Text To Audio task"""
audio: Any """The generated audio waveform.""" sampling_rate: float """The sampling rate of the generated audio waveform."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass TextToImageParameters(BaseInferenceType): """Additional inference parameters for Text To Image"""
guidance_scale: float | None = None """A higher guidance scale value encourages the model to generate images closely linked to the text prompt, but values too high may cause saturation and other artifacts. """ height: int | None = None """The height in pixels of the output image""" negative_prompt: str | None = None """One prompt to guide what NOT to include in image generation.""" num_inference_steps: int | None = None """The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference. """ scheduler: str | None = None """Override the scheduler with a compatible one.""" seed: int | None = None """Seed for the random number generator.""" width: int | None = None """The width in pixels of the output image"""
@dataclass_with_extraclass TextToImageInput(BaseInferenceType): """Inputs for Text To Image inference"""
inputs: str """The input text data (sometimes called "prompt")""" parameters: TextToImageParameters | None = None """Additional inference parameters for Text To Image"""
@dataclass_with_extraclass TextToImageOutput(BaseInferenceType): """Outputs of inference for the Text To Image task"""
image: Any """The generated image returned as raw bytes in the payload."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any, Literal, Union
from .base import BaseInferenceType, dataclass_with_extra
TextToSpeechEarlyStoppingEnum = Literal["never"]
@dataclass_with_extraclass TextToSpeechGenerationParameters(BaseInferenceType): """Parametrization of the text generation process"""
do_sample: bool | None = None """Whether to use sampling instead of greedy decoding when generating new tokens.""" early_stopping: Union[bool, "TextToSpeechEarlyStoppingEnum"] | None = None """Controls the stopping condition for beam-based methods.""" epsilon_cutoff: float | None = None """If set to float strictly between 0 and 1, only tokens with a conditional probability greater than epsilon_cutoff will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) for more details. """ eta_cutoff: float | None = None """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) for more details. """ max_length: int | None = None """The maximum length (in tokens) of the generated text, including the input.""" max_new_tokens: int | None = None """The maximum number of tokens to generate. Takes precedence over max_length.""" min_length: int | None = None """The minimum length (in tokens) of the generated text, including the input.""" min_new_tokens: int | None = None """The minimum number of tokens to generate. Takes precedence over min_length.""" num_beam_groups: int | None = None """Number of groups to divide num_beams into in order to ensure diversity among different groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details. """ num_beams: int | None = None """Number of beams to use for beam search.""" penalty_alpha: float | None = None """The value balances the model confidence and the degeneration penalty in contrastive search decoding. """ temperature: float | None = None """The value used to modulate the next token probabilities.""" top_k: int | None = None """The number of highest probability vocabulary tokens to keep for top-k-filtering.""" top_p: float | None = None """If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. """ typical_p: float | None = None """Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to typical_p or higher are kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details. """ use_cache: bool | None = None """Whether the model should use the past last key/values attentions to speed up decoding"""
@dataclass_with_extraclass TextToSpeechParameters(BaseInferenceType): """Additional inference parameters for Text To Speech"""
generation_parameters: TextToSpeechGenerationParameters | None = None """Parametrization of the text generation process"""
@dataclass_with_extraclass TextToSpeechInput(BaseInferenceType): """Inputs for Text To Speech inference"""
inputs: str """The input text data""" parameters: TextToSpeechParameters | None = None """Additional inference parameters for Text To Speech"""
@dataclass_with_extraclass TextToSpeechOutput(BaseInferenceType): """Outputs of inference for the Text To Speech task"""
audio: Any """The generated audio""" sampling_rate: float | None = None """The sampling rate of the generated audio waveform."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass TextToVideoParameters(BaseInferenceType): """Additional inference parameters for Text To Video"""
guidance_scale: float | None = None """A higher guidance scale value encourages the model to generate videos closely linked to the text prompt, but values too high may cause saturation and other artifacts. """ negative_prompt: list[str] | None = None """One or several prompt to guide what NOT to include in video generation.""" num_frames: float | None = None """The num_frames parameter determines how many video frames are generated.""" num_inference_steps: int | None = None """The number of denoising steps. More denoising steps usually lead to a higher quality video at the expense of slower inference. """ seed: int | None = None """Seed for the random number generator."""
@dataclass_with_extraclass TextToVideoInput(BaseInferenceType): """Inputs for Text To Video inference"""
inputs: str """The input text data (sometimes called "prompt")""" parameters: TextToVideoParameters | None = None """Additional inference parameters for Text To Video"""
@dataclass_with_extraclass TextToVideoOutput(BaseInferenceType): """Outputs of inference for the Text To Video task"""
video: Any """The generated video returned as raw bytes in the payload."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Literal, Optional
from .base import BaseInferenceType, dataclass_with_extra
TokenClassificationAggregationStrategy = Literal["none", "simple", "first", "average", "max"]
@dataclass_with_extraclass TokenClassificationParameters(BaseInferenceType): """Additional inference parameters for Token Classification"""
aggregation_strategy: Optional["TokenClassificationAggregationStrategy"] = None """The strategy used to fuse tokens based on model predictions""" ignore_labels: list[str] | None = None """A list of labels to ignore""" stride: int | None = None """The number of overlapping tokens between chunks when splitting the input text."""
@dataclass_with_extraclass TokenClassificationInput(BaseInferenceType): """Inputs for Token Classification inference"""
inputs: str """The input text data""" parameters: TokenClassificationParameters | None = None """Additional inference parameters for Token Classification"""
@dataclass_with_extraclass TokenClassificationOutputElement(BaseInferenceType): """Outputs of inference for the Token Classification task"""
end: int """The character position in the input where this group ends.""" score: float """The associated score / probability""" start: int """The character position in the input where this group begins.""" word: str """The corresponding text""" entity: str | None = None """The predicted label for a single token""" entity_group: str | None = None """The predicted label for a group of one or more tokens"""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any, Literal, Optional
from .base import BaseInferenceType, dataclass_with_extra
TranslationTruncationStrategy = Literal["do_not_truncate", "longest_first", "only_first", "only_second"]
@dataclass_with_extraclass TranslationParameters(BaseInferenceType): """Additional inference parameters for Translation"""
clean_up_tokenization_spaces: bool | None = None """Whether to clean up the potential extra spaces in the text output.""" generate_parameters: dict[str, Any] | None = None """Additional parametrization of the text generation algorithm.""" src_lang: str | None = None """The source language of the text. Required for models that can translate from multiple languages. """ tgt_lang: str | None = None """Target language to translate to. Required for models that can translate to multiple languages. """ truncation: Optional["TranslationTruncationStrategy"] = None """The truncation strategy to use."""
@dataclass_with_extraclass TranslationInput(BaseInferenceType): """Inputs for Translation inference"""
inputs: str """The text to translate.""" parameters: TranslationParameters | None = None """Additional inference parameters for Translation"""
@dataclass_with_extraclass TranslationOutput(BaseInferenceType): """Outputs of inference for the Translation task"""
translation_text: str """The translated text."""123456789101112131415161718192021222324252627282930313233343536373839404142434445# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any, Literal, Optional
from .base import BaseInferenceType, dataclass_with_extra
VideoClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
@dataclass_with_extraclass VideoClassificationParameters(BaseInferenceType): """Additional inference parameters for Video Classification"""
frame_sampling_rate: int | None = None """The sampling rate used to select frames from the video.""" function_to_apply: Optional["VideoClassificationOutputTransform"] = None """The function to apply to the model outputs in order to retrieve the scores.""" num_frames: int | None = None """The number of sampled frames to consider for classification.""" top_k: int | None = None """When specified, limits the output to the top K most probable classes."""
@dataclass_with_extraclass VideoClassificationInput(BaseInferenceType): """Inputs for Video Classification inference"""
inputs: Any """The input video data""" parameters: VideoClassificationParameters | None = None """Additional inference parameters for Video Classification"""
@dataclass_with_extraclass VideoClassificationOutputElement(BaseInferenceType): """Outputs of inference for the Video Classification task"""
label: str """The predicted class label.""" score: float """The corresponding probability."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from typing import Any
from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass VisualQuestionAnsweringInputData(BaseInferenceType): """One (image, question) pair to answer"""
image: Any """The image.""" question: str """The question to answer based on the image."""
@dataclass_with_extraclass VisualQuestionAnsweringParameters(BaseInferenceType): """Additional inference parameters for Visual Question Answering"""
top_k: int | None = None """The number of answers to return (will be chosen by order of likelihood). Note that we return less than topk answers if there are not enough options available within the context. """
@dataclass_with_extraclass VisualQuestionAnsweringInput(BaseInferenceType): """Inputs for Visual Question Answering inference"""
inputs: VisualQuestionAnsweringInputData """One (image, question) pair to answer""" parameters: VisualQuestionAnsweringParameters | None = None """Additional inference parameters for Visual Question Answering"""
@dataclass_with_extraclass VisualQuestionAnsweringOutputElement(BaseInferenceType): """Outputs of inference for the Visual Question Answering task"""
score: float """The associated score / probability""" answer: str | None = None """The answer to the question"""12345678910111213141516171819202122232425262728293031323334353637383940414243# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass ZeroShotClassificationParameters(BaseInferenceType): """Additional inference parameters for Zero Shot Classification"""
candidate_labels: list[str] """The set of possible class labels to classify the text into.""" hypothesis_template: str | None = None """The sentence used in conjunction with `candidate_labels` to attempt the text classification by replacing the placeholder with the candidate labels. """ multi_label: bool | None = None """Whether multiple candidate labels can be true. If false, the scores are normalized such that the sum of the label likelihoods for each sequence is 1. If true, the labels are considered independent and probabilities are normalized for each candidate. """
@dataclass_with_extraclass ZeroShotClassificationInput(BaseInferenceType): """Inputs for Zero Shot Classification inference"""
inputs: str """The text to classify""" parameters: ZeroShotClassificationParameters """Additional inference parameters for Zero Shot Classification"""
@dataclass_with_extraclass ZeroShotClassificationOutputElement(BaseInferenceType): """Outputs of inference for the Zero Shot Classification task"""
label: str """The predicted class label.""" score: float """The corresponding probability."""1234567891011121314151617181920212223242526272829303132333435363738# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass ZeroShotImageClassificationParameters(BaseInferenceType): """Additional inference parameters for Zero Shot Image Classification"""
candidate_labels: list[str] """The candidate labels for this image""" hypothesis_template: str | None = None """The sentence used in conjunction with `candidate_labels` to attempt the image classification by replacing the placeholder with the candidate labels. """
@dataclass_with_extraclass ZeroShotImageClassificationInput(BaseInferenceType): """Inputs for Zero Shot Image Classification inference"""
inputs: str """The input image data to classify as a base64-encoded string.""" parameters: ZeroShotImageClassificationParameters """Additional inference parameters for Zero Shot Image Classification"""
@dataclass_with_extraclass ZeroShotImageClassificationOutputElement(BaseInferenceType): """Outputs of inference for the Zero Shot Image Classification task"""
label: str """The predicted class label.""" score: float """The corresponding probability."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# Inference code generated from the JSON schema spec in @huggingface/tasks.## See:# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.from .base import BaseInferenceType, dataclass_with_extra
@dataclass_with_extraclass ZeroShotObjectDetectionParameters(BaseInferenceType): """Additional inference parameters for Zero Shot Object Detection"""
candidate_labels: list[str] """The candidate labels for this image"""
@dataclass_with_extraclass ZeroShotObjectDetectionInput(BaseInferenceType): """Inputs for Zero Shot Object Detection inference"""
inputs: str """The input image data as a base64-encoded string.""" parameters: ZeroShotObjectDetectionParameters """Additional inference parameters for Zero Shot Object Detection"""
@dataclass_with_extraclass ZeroShotObjectDetectionBoundingBox(BaseInferenceType): """The predicted bounding box. Coordinates are relative to the top left corner of the input image. """
xmax: int xmin: int ymax: int ymin: int
@dataclass_with_extraclass ZeroShotObjectDetectionOutputElement(BaseInferenceType): """Outputs of inference for the Zero Shot Object Detection task"""
box: ZeroShotObjectDetectionBoundingBox """The predicted bounding box. Coordinates are relative to the top left corner of the input image. """ label: str """A candidate label""" score: float """The associated score / probability"""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import asyncioimport sysfrom functools import partial
import typer
def _patch_anyio_open_process(): """ Patch anyio.open_process to allow detached processes on Windows and Unix-like systems.
This is necessary to prevent the MCP client from being interrupted by Ctrl+C when running in the CLI. """ import subprocess
import anyio
if getattr(anyio, "_tiny_agents_patched", False): return anyio._tiny_agents_patched = True # ty: ignore[invalid-assignment]
original_open_process = anyio.open_process
if sys.platform == "win32": # On Windows, we need to set the creation flags to create a new process group
async def open_process_in_new_group(*args, **kwargs): """ Wrapper for open_process to handle Windows-specific process creation flags. """ # Ensure we pass the creation flags for Windows kwargs.setdefault("creationflags", subprocess.CREATE_NEW_PROCESS_GROUP) return await original_open_process(*args, **kwargs)
anyio.open_process = open_process_in_new_group # ty: ignore[invalid-assignment] else: # For Unix-like systems, we can use setsid to create a new session async def open_process_in_new_group(*args, **kwargs): """ Wrapper for open_process to handle Unix-like systems with start_new_session=True. """ kwargs.setdefault("start_new_session", True) return await original_open_process(*args, **kwargs)
anyio.open_process = open_process_in_new_group # ty: ignore[invalid-assignment]
async def _async_prompt(exit_event: asyncio.Event, prompt: str = "» ") -> str: """ Asynchronous prompt function that reads input from stdin without blocking.
This function is designed to work in an asynchronous context, allowing the event loop to gracefully stop it (e.g. on Ctrl+C).
Alternatively, we could use https://github.com/vxgmichel/aioconsole but that would be an additional dependency. """ loop = asyncio.get_event_loop()
if sys.platform == "win32": # Windows: Use run_in_executor to avoid blocking the event loop # Degraded solution: this is not ideal as user will have to CTRL+C once more to stop the prompt (and it'll not be graceful) return await loop.run_in_executor(None, partial(typer.prompt, prompt, prompt_suffix=" ")) else: # UNIX-like: Use loop.add_reader for non-blocking stdin read future = loop.create_future()
def on_input(): line = sys.stdin.readline() loop.remove_reader(sys.stdin) future.set_result(line)
print(prompt, end=" ", flush=True) loop.add_reader(sys.stdin, on_input) # not supported on Windows
# Wait for user input or exit event # Wait until either the user hits enter or exit_event is set exit_task = asyncio.create_task(exit_event.wait()) await asyncio.wait( [future, exit_task], return_when=asyncio.FIRST_COMPLETED, )
# Check which one has been triggered if exit_event.is_set(): future.cancel() return ""
line = await future return line.strip()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100from __future__ import annotations
import asynciofrom typing import AsyncGenerator, Iterable, Optional, Union
from huggingface_hub import ChatCompletionInputMessage, ChatCompletionStreamOutput, MCPClient
from .._providers import PROVIDER_OR_POLICY_Tfrom .constants import DEFAULT_SYSTEM_PROMPT, EXIT_LOOP_TOOLS, MAX_NUM_TURNSfrom .types import ServerConfig
class Agent(MCPClient): """ Implementation of a Simple Agent, which is a simple while loop built right on top of an [`MCPClient`].
> [!WARNING] > This class is experimental and might be subject to breaking changes in the future without prior notice.
Args: model (`str`, *optional*): The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. `meta-llama/Meta-Llama-3-8B-Instruct` or a URL to a deployed Inference Endpoint or other local or remote endpoint. servers (`Iterable[dict]`): MCP servers to connect to. Each server is a dictionary containing a `type` key and a `config` key. The `type` key can be `"stdio"` or `"sse"`, and the `config` key is a dictionary of arguments for the server. provider (`str`, *optional*): Name of the provider to use for inference. Defaults to "auto" i.e. the first of the providers available for the model, sorted by the user's order in https://hf.co/settings/inference-providers. If model is a URL or `base_url` is passed, then `provider` is not used. base_url (`str`, *optional*): The base URL to run inference. Defaults to None. api_key (`str`, *optional*): Token to use for authentication. Will default to the locally Hugging Face saved token if not provided. You can also use your own provider API key to interact directly with the provider's service. prompt (`str`, *optional*): The system prompt to use for the agent. Defaults to the default system prompt in `constants.py`. """
def __init__( self, *, model: Optional[str] = None, servers: Iterable[ServerConfig], provider: Optional[PROVIDER_OR_POLICY_T] = None, base_url: Optional[str] = None, api_key: Optional[str] = None, prompt: Optional[str] = None, ): super().__init__(model=model, provider=provider, base_url=base_url, api_key=api_key) self._servers_cfg = list(servers) self.messages: list[Union[dict, ChatCompletionInputMessage]] = [ {"role": "system", "content": prompt or DEFAULT_SYSTEM_PROMPT} ]
async def load_tools(self) -> None: for cfg in self._servers_cfg: await self.add_mcp_server(**cfg)
async def run( self, user_input: str, *, abort_event: Optional[asyncio.Event] = None, ) -> AsyncGenerator[Union[ChatCompletionStreamOutput, ChatCompletionInputMessage], None]: """ Run the agent with the given user input.
Args: user_input (`str`): The user input to run the agent with. abort_event (`asyncio.Event`, *optional*): An event that can be used to abort the agent. If the event is set, the agent will stop running. """ self.messages.append({"role": "user", "content": user_input})
num_turns: int = 0 next_turn_should_call_tools = True
while True: if abort_event and abort_event.is_set(): return
async for item in self.process_single_turn_with_tools( self.messages, exit_loop_tools=EXIT_LOOP_TOOLS, exit_if_first_chunk_no_tool=(num_turns > 0 and next_turn_should_call_tools), ): yield item
num_turns += 1 last = self.messages[-1]
if last.get("role") == "tool" and last.get("name") in {t.function.name for t in EXIT_LOOP_TOOLS}: return
if last.get("role") != "tool" and num_turns > MAX_NUM_TURNS: return
if last.get("role") != "tool" and next_turn_should_call_tools: return
next_turn_should_call_tools = last.get("role") != "tool"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255import asyncioimport osimport signalimport tracebackfrom typing import Optional
import typer
from ...utils import ANSIfrom ._cli_hacks import _async_prompt, _patch_anyio_open_processfrom .agent import Agentfrom .utils import _load_agent_config
app = typer.Typer( rich_markup_mode="rich", help="A squad of lightweight composable AI applications built on Hugging Face's Inference Client and MCP stack.",)
run_cli = typer.Typer( name="run", help="Run the Agent in the CLI", invoke_without_command=True,)app.add_typer(run_cli, name="run")
async def run_agent( agent_path: Optional[str],) -> None: """ Tiny Agent loop.
Args: agent_path (`str`, *optional*): Path to a local folder containing an `agent.json` and optionally a custom `PROMPT.md` or `AGENTS.md` file or a built-in agent stored in a Hugging Face dataset.
""" _patch_anyio_open_process() # Hacky way to prevent stdio connections to be stopped by Ctrl+C
config, prompt = _load_agent_config(agent_path)
inputs = config.get("inputs", []) servers = config.get("servers", [])
abort_event = asyncio.Event() exit_event = asyncio.Event() first_sigint = True
loop = asyncio.get_running_loop() original_sigint_handler = signal.getsignal(signal.SIGINT)
def _sigint_handler() -> None: nonlocal first_sigint if first_sigint: first_sigint = False abort_event.set() print(ANSI.red("\nInterrupted. Press Ctrl+C again to quit."), flush=True) return
print(ANSI.red("\nExiting..."), flush=True) exit_event.set()
try: sigint_registered_in_loop = False try: loop.add_signal_handler(signal.SIGINT, _sigint_handler) sigint_registered_in_loop = True except (AttributeError, NotImplementedError): # Windows (or any loop that doesn't support it) : fall back to sync signal.signal(signal.SIGINT, lambda *_: _sigint_handler())
# Handle inputs (i.e. env variables injection) resolved_inputs: dict[str, str] = {}
if len(inputs) > 0: print( ANSI.bold( ANSI.blue( "Some initial inputs are required by the agent. " "Please provide a value or leave empty to load from env." ) ) ) for input_item in inputs: input_id = input_item["id"] description = input_item["description"] env_special_value = f"${{input:{input_id}}}"
# Check if the input is used by any server or as an apiKey input_usages = set() for server in servers: # Check stdio's "env" and http/sse's "headers" mappings env_or_headers = server.get("env", {}) if server["type"] == "stdio" else server.get("headers", {}) for key, value in env_or_headers.items(): if env_special_value in value: input_usages.add(key)
raw_api_key = config.get("apiKey") if isinstance(raw_api_key, str) and env_special_value in raw_api_key: input_usages.add("apiKey")
if not input_usages: print( ANSI.yellow( f"Input '{input_id}' defined in config but not used by any server or as an API key." " Skipping." ) ) continue
# Prompt user for input env_variable_key = input_id.replace("-", "_").upper() print( ANSI.blue(f" • {input_id}") + f": {description}. (default: load from {env_variable_key}).", end=" ", ) user_input = (await _async_prompt(exit_event=exit_event)).strip() if exit_event.is_set(): return
# Fallback to environment variable when user left blank final_value = user_input if not final_value: final_value = os.getenv(env_variable_key, "") if final_value: print(ANSI.green(f"Value successfully loaded from '{env_variable_key}'")) else: print( ANSI.yellow( f"No value found for '{env_variable_key}' in environment variables. Continuing." ) ) resolved_inputs[input_id] = final_value
# Inject resolved value (can be empty) into stdio's env or http/sse's headers for server in servers: env_or_headers = server.get("env", {}) if server["type"] == "stdio" else server.get("headers", {}) for key, value in env_or_headers.items(): if env_special_value in value: env_or_headers[key] = env_or_headers[key].replace(env_special_value, final_value)
print()
raw_api_key = config.get("apiKey") if isinstance(raw_api_key, str): substituted_api_key = raw_api_key for input_id, val in resolved_inputs.items(): substituted_api_key = substituted_api_key.replace(f"${{input:{input_id}}}", val) config["apiKey"] = substituted_api_key # Main agent loop async with Agent( provider=config.get("provider"), # type: ignore model=config.get("model"), base_url=config.get("endpointUrl"), # type: ignore[arg-type] api_key=config.get("apiKey"), servers=servers, # type: ignore[arg-type] prompt=prompt, ) as agent: await agent.load_tools() print(ANSI.bold(ANSI.blue("Agent loaded with {} tools:".format(len(agent.available_tools))))) for t in agent.available_tools: print(ANSI.blue(f" • {t.function.name}"))
while True: abort_event.clear()
# Check if we should exit if exit_event.is_set(): return
try: user_input = await _async_prompt(exit_event=exit_event) first_sigint = True except EOFError: print(ANSI.red("\nEOF received, exiting."), flush=True) break except KeyboardInterrupt: if not first_sigint and abort_event.is_set(): continue else: print(ANSI.red("\nKeyboard interrupt during input processing."), flush=True) break
try: async for chunk in agent.run(user_input, abort_event=abort_event): if abort_event.is_set() and not first_sigint: break if exit_event.is_set(): return
if hasattr(chunk, "choices"): delta = chunk.choices[0].delta if delta.content: print(delta.content, end="", flush=True) if delta.tool_calls: for call in delta.tool_calls: if call.id: print(f"<Tool {call.id}>", end="") if call.function.name: print(f"{call.function.name}", end=" ") if call.function.arguments: print(f"{call.function.arguments}", end="") else: print( ANSI.green(f"\n\nTool[{chunk.name}] {chunk.tool_call_id}\n{chunk.content}\n"), flush=True, )
print()
except Exception as e: tb_str = traceback.format_exc() print(ANSI.red(f"\nError during agent run: {e}\n{tb_str}"), flush=True) first_sigint = True # Allow graceful interrupt for the next command
except Exception as e: tb_str = traceback.format_exc() print(ANSI.red(f"\nAn unexpected error occurred: {e}\n{tb_str}"), flush=True) raise e
finally: if sigint_registered_in_loop: try: loop.remove_signal_handler(signal.SIGINT) except (AttributeError, NotImplementedError): pass else: signal.signal(signal.SIGINT, original_sigint_handler)
@run_cli.callback()def run( path: Optional[str] = typer.Argument( None, help=( "Path to a local folder containing an agent.json file or a built-in agent " "stored in the 'tiny-agents/tiny-agents' Hugging Face dataset " "(https://huggingface.co/datasets/tiny-agents/tiny-agents)" ), show_default=False, ),): try: asyncio.run(run_agent(path)) except KeyboardInterrupt: print(ANSI.red("\nApplication terminated by KeyboardInterrupt."), flush=True) raise typer.Exit(code=130) except Exception as e: print(ANSI.red(f"\nAn unexpected error occurred: {e}"), flush=True) raise e
if __name__ == "__main__": app()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081from __future__ import annotations
import sysfrom pathlib import Path
from huggingface_hub import ChatCompletionInputTool
FILENAME_CONFIG = "agent.json"PROMPT_FILENAMES = ("PROMPT.md", "AGENTS.md")
DEFAULT_AGENT = { "model": "Qwen/Qwen2.5-72B-Instruct", "provider": "nebius", "servers": [ { "type": "stdio", "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", str(Path.home() / ("Desktop" if sys.platform == "darwin" else "")), ], }, { "type": "stdio", "command": "npx", "args": ["@playwright/mcp@latest"], }, ],}
DEFAULT_SYSTEM_PROMPT = """You are an agent - please keep going until the user’s query is completelyresolved, before ending your turn and yielding back to the user. Only terminateyour turn when you are sure that the problem is solved, or if you need moreinfo from the user to solve the problem.If you are not sure about anything pertaining to the user’s request, use yourtools to read files and gather the relevant information: do NOT guess or makeup an answer.You MUST plan extensively before each function call, and reflect extensivelyon the outcomes of the previous function calls. DO NOT do this entire processby making function calls only, as this can impair your ability to solve theproblem and think insightfully.""".strip()
MAX_NUM_TURNS = 10
TASK_COMPLETE_TOOL: ChatCompletionInputTool = ChatCompletionInputTool.parse_obj( # type: ignore { "type": "function", "function": { "name": "task_complete", "description": "Call this tool when the task given by the user is complete", "parameters": { "type": "object", "properties": {}, }, }, })
ASK_QUESTION_TOOL: ChatCompletionInputTool = ChatCompletionInputTool.parse_obj( # type: ignore { "type": "function", "function": { "name": "ask_question", "description": "Ask the user for more info required to solve or clarify their problem.", "parameters": { "type": "object", "properties": {}, }, }, })
EXIT_LOOP_TOOLS: list[ChatCompletionInputTool] = [TASK_COMPLETE_TOOL, ASK_QUESTION_TOOL]
DEFAULT_REPO_ID = "tiny-agents/tiny-agents"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395import jsonimport loggingfrom contextlib import AsyncExitStackfrom datetime import timedeltafrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, AsyncIterable, Literal, Optional, TypedDict, Union, overload
from typing_extensions import NotRequired, TypeAlias, Unpack
from ...utils._runtime import get_hf_hub_versionfrom .._generated._async_client import AsyncInferenceClientfrom .._generated.types import ( ChatCompletionInputMessage, ChatCompletionInputTool, ChatCompletionStreamOutput, ChatCompletionStreamOutputDeltaToolCall,)from .._providers import PROVIDER_OR_POLICY_Tfrom .utils import format_result
if TYPE_CHECKING: from mcp import ClientSession
logger = logging.getLogger(__name__)
# Type alias for tool namesToolName: TypeAlias = str
ServerType: TypeAlias = Literal["stdio", "sse", "http"]
class StdioServerParameters_T(TypedDict): command: str args: NotRequired[list[str]] env: NotRequired[dict[str, str]] cwd: NotRequired[Union[str, Path, None]]
class SSEServerParameters_T(TypedDict): url: str headers: NotRequired[dict[str, Any]] timeout: NotRequired[float] sse_read_timeout: NotRequired[float]
class StreamableHTTPParameters_T(TypedDict): url: str headers: NotRequired[dict[str, Any]] timeout: NotRequired[timedelta] sse_read_timeout: NotRequired[timedelta] terminate_on_close: NotRequired[bool]
class MCPClient: """ Client for connecting to one or more MCP servers and processing chat completions with tools.
> [!WARNING] > This class is experimental and might be subject to breaking changes in the future without prior notice.
Args: model (`str`, `optional`): The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. `meta-llama/Meta-Llama-3-8B-Instruct` or a URL to a deployed Inference Endpoint or other local or remote endpoint. provider (`str`, *optional*): Name of the provider to use for inference. Defaults to "auto" i.e. the first of the providers available for the model, sorted by the user's order in https://hf.co/settings/inference-providers. If model is a URL or `base_url` is passed, then `provider` is not used. base_url (`str`, *optional*): The base URL to run inference. Defaults to None. api_key (`str`, `optional`): Token to use for authentication. Will default to the locally Hugging Face saved token if not provided. You can also use your own provider API key to interact directly with the provider's service. """
def __init__( self, *, model: Optional[str] = None, provider: Optional[PROVIDER_OR_POLICY_T] = None, base_url: Optional[str] = None, api_key: Optional[str] = None, ): # Initialize MCP sessions as a dictionary of ClientSession objects self.sessions: dict[ToolName, "ClientSession"] = {} self.exit_stack = AsyncExitStack() self.available_tools: list[ChatCompletionInputTool] = [] # To be able to send the model in the payload if `base_url` is provided if model is None and base_url is None: raise ValueError("At least one of `model` or `base_url` should be set in `MCPClient`.") self.payload_model = model self.client = AsyncInferenceClient( model=None if base_url is not None else model, provider=provider, api_key=api_key, base_url=base_url, )
async def __aenter__(self): """Enter the context manager""" await self.client.__aenter__() await self.exit_stack.__aenter__() return self
async def __aexit__(self, exc_type, exc_val, exc_tb): """Exit the context manager""" await self.client.__aexit__(exc_type, exc_val, exc_tb) await self.cleanup()
async def cleanup(self): """Clean up resources""" await self.client.close() await self.exit_stack.aclose()
@overload async def add_mcp_server(self, type: Literal["stdio"], **params: Unpack[StdioServerParameters_T]): ...
@overload async def add_mcp_server(self, type: Literal["sse"], **params: Unpack[SSEServerParameters_T]): ...
@overload async def add_mcp_server(self, type: Literal["http"], **params: Unpack[StreamableHTTPParameters_T]): ...
async def add_mcp_server(self, type: ServerType, **params: Any): """Connect to an MCP server
Args: type (`str`): Type of the server to connect to. Can be one of: - "stdio": Standard input/output server (local) - "sse": Server-sent events (SSE) server - "http": StreamableHTTP server **params (`dict[str, Any]`): Server parameters that can be either: - For stdio servers: - command (str): The command to run the MCP server - args (list[str], optional): Arguments for the command - env (dict[str, str], optional): Environment variables for the command - cwd (Union[str, Path, None], optional): Working directory for the command - allowed_tools (list[str], optional): List of tool names to allow from this server - For SSE servers: - url (str): The URL of the SSE server - headers (dict[str, Any], optional): Headers for the SSE connection - timeout (float, optional): Connection timeout - sse_read_timeout (float, optional): SSE read timeout - allowed_tools (list[str], optional): List of tool names to allow from this server - For StreamableHTTP servers: - url (str): The URL of the StreamableHTTP server - headers (dict[str, Any], optional): Headers for the StreamableHTTP connection - timeout (timedelta, optional): Connection timeout - sse_read_timeout (timedelta, optional): SSE read timeout - terminate_on_close (bool, optional): Whether to terminate on close - allowed_tools (list[str], optional): List of tool names to allow from this server """ from mcp import ClientSession, StdioServerParameters from mcp import types as mcp_types
# Extract allowed_tools configuration if provided allowed_tools = params.pop("allowed_tools", None)
# Determine server type and create appropriate parameters if type == "stdio": # Handle stdio server from mcp.client.stdio import stdio_client
logger.info(f"Connecting to stdio MCP server with command: {params['command']} {params.get('args', [])}")
client_kwargs = {"command": params["command"]} for key in ["args", "env", "cwd"]: if params.get(key) is not None: client_kwargs[key] = params[key] server_params = StdioServerParameters(**client_kwargs) read, write = await self.exit_stack.enter_async_context(stdio_client(server_params)) elif type == "sse": # Handle SSE server from mcp.client.sse import sse_client
logger.info(f"Connecting to SSE MCP server at: {params['url']}")
client_kwargs = {"url": params["url"]} for key in ["headers", "timeout", "sse_read_timeout"]: if params.get(key) is not None: client_kwargs[key] = params[key] read, write = await self.exit_stack.enter_async_context(sse_client(**client_kwargs)) elif type == "http": # Handle StreamableHTTP server from mcp.client.streamable_http import streamablehttp_client
logger.info(f"Connecting to StreamableHTTP MCP server at: {params['url']}")
client_kwargs = {"url": params["url"]} for key in ["headers", "timeout", "sse_read_timeout", "terminate_on_close"]: if params.get(key) is not None: client_kwargs[key] = params[key] read, write, _ = await self.exit_stack.enter_async_context(streamablehttp_client(**client_kwargs)) # ^ TODO: should be handle `get_session_id_callback`? (function to retrieve the current session ID) else: raise ValueError(f"Unsupported server type: {type}")
session = await self.exit_stack.enter_async_context( ClientSession( read_stream=read, write_stream=write, client_info=mcp_types.Implementation( name="huggingface_hub.MCPClient", version=get_hf_hub_version(), ), ) )
logger.debug("Initializing session...") await session.initialize()
# List available tools response = await session.list_tools() logger.debug("Connected to server with tools:", [tool.name for tool in response.tools])
# Filter tools based on allowed_tools configuration filtered_tools = response.tools
if allowed_tools is not None: filtered_tools = [tool for tool in response.tools if tool.name in allowed_tools] logger.debug( f"Tool filtering applied. Using {len(filtered_tools)} of {len(response.tools)} available tools: {[tool.name for tool in filtered_tools]}" )
for tool in filtered_tools: if tool.name in self.sessions: logger.warning(f"Tool '{tool.name}' already defined by another server. Skipping.") continue
# Map tool names to their server for later lookup self.sessions[tool.name] = session
# Add tool to the list of available tools (for use in chat completions) self.available_tools.append( ChatCompletionInputTool.parse_obj_as_instance( { "type": "function", "function": { "name": tool.name, "description": tool.description, "parameters": tool.inputSchema, }, } ) )
async def process_single_turn_with_tools( self, messages: list[Union[dict, ChatCompletionInputMessage]], exit_loop_tools: Optional[list[ChatCompletionInputTool]] = None, exit_if_first_chunk_no_tool: bool = False, ) -> AsyncIterable[Union[ChatCompletionStreamOutput, ChatCompletionInputMessage]]: """Process a query using `self.model` and available tools, yielding chunks and tool outputs.
Args: messages (`list[dict]`): List of message objects representing the conversation history exit_loop_tools (`list[ChatCompletionInputTool]`, *optional*): List of tools that should exit the generator when called exit_if_first_chunk_no_tool (`bool`, *optional*): Exit if no tool is present in the first chunks. Default to False.
Yields: [`ChatCompletionStreamOutput`] chunks or [`ChatCompletionInputMessage`] objects """ # Prepare tools list based on options tools = self.available_tools if exit_loop_tools is not None: tools = [*exit_loop_tools, *self.available_tools]
# Create the streaming request response = await self.client.chat.completions.create( model=self.payload_model, messages=messages, tools=tools, tool_choice="auto", stream=True, )
message: dict[str, Any] = {"role": "unknown", "content": ""} final_tool_calls: dict[int, ChatCompletionStreamOutputDeltaToolCall] = {} num_of_chunks = 0
# Read from stream async for chunk in response: num_of_chunks += 1 delta = chunk.choices[0].delta if chunk.choices and len(chunk.choices) > 0 else None if not delta: continue
# Process message if delta.role: message["role"] = delta.role if delta.content: message["content"] += delta.content
# Process tool calls if delta.tool_calls: for tool_call in delta.tool_calls: idx = tool_call.index # first chunk for this tool call if idx not in final_tool_calls: final_tool_calls[idx] = tool_call if final_tool_calls[idx].function.arguments is None: final_tool_calls[idx].function.arguments = "" continue # safety before concatenating text to .function.arguments if final_tool_calls[idx].function.arguments is None: final_tool_calls[idx].function.arguments = ""
if tool_call.function.arguments: final_tool_calls[idx].function.arguments += tool_call.function.arguments
# Optionally exit early if no tools in first chunks if exit_if_first_chunk_no_tool and num_of_chunks <= 2 and len(final_tool_calls) == 0: return
# Yield each chunk to caller yield chunk
# Add the assistant message with tool calls (if any) to messages if message["content"] or final_tool_calls: # if the role is unknown, set it to assistant if message.get("role") == "unknown": message["role"] = "assistant" # Convert final_tool_calls to the format expected by OpenAI if final_tool_calls: tool_calls_list: list[dict[str, Any]] = [] for tc in final_tool_calls.values(): tool_calls_list.append( { "id": tc.id, "type": "function", "function": { "name": tc.function.name, "arguments": tc.function.arguments or "{}", }, } ) message["tool_calls"] = tool_calls_list messages.append(message)
# Process tool calls one by one for tool_call in final_tool_calls.values(): function_name = tool_call.function.name if function_name is None: message = ChatCompletionInputMessage.parse_obj_as_instance( { "role": "tool", "tool_call_id": tool_call.id, "content": "Invalid tool call with no function name.", } ) messages.append(message) yield message continue # move to next tool call try: function_args = json.loads(tool_call.function.arguments or "{}") except json.JSONDecodeError as err: tool_message = { "role": "tool", "tool_call_id": tool_call.id, "name": function_name, "content": f"Invalid JSON generated by the model: {err}", } tool_message_as_obj = ChatCompletionInputMessage.parse_obj_as_instance(tool_message) messages.append(tool_message_as_obj) yield tool_message_as_obj continue # move to next tool call
tool_message = {"role": "tool", "tool_call_id": tool_call.id, "content": "", "name": function_name}
# Check if this is an exit loop tool if exit_loop_tools and function_name in [t.function.name for t in exit_loop_tools]: tool_message_as_obj = ChatCompletionInputMessage.parse_obj_as_instance(tool_message) messages.append(tool_message_as_obj) yield tool_message_as_obj return
# Execute tool call with the appropriate session session = self.sessions.get(function_name) if session is not None: try: result = await session.call_tool(function_name, function_args) tool_message["content"] = format_result(result) except Exception as err: tool_message["content"] = f"Error: MCP tool call failed with error message: {err}" else: tool_message["content"] = f"Error: No session found for tool: {function_name}"
# Yield tool message tool_message_as_obj = ChatCompletionInputMessage.parse_obj_as_instance(tool_message) messages.append(tool_message_as_obj) yield tool_message_as_obj123456789101112131415161718192021222324252627282930313233343536373839404142434445from typing import Literal, TypedDict, Union
from typing_extensions import NotRequired
class InputConfig(TypedDict, total=False): id: str description: str type: str password: bool
class StdioServerConfig(TypedDict): type: Literal["stdio"] command: str args: list[str] env: dict[str, str] cwd: str allowed_tools: NotRequired[list[str]]
class HTTPServerConfig(TypedDict): type: Literal["http"] url: str headers: dict[str, str] allowed_tools: NotRequired[list[str]]
class SSEServerConfig(TypedDict): type: Literal["sse"] url: str headers: dict[str, str] allowed_tools: NotRequired[list[str]]
ServerConfig = Union[StdioServerConfig, HTTPServerConfig, SSEServerConfig]
# AgentConfig root objectclass AgentConfig(TypedDict): model: str provider: str apiKey: NotRequired[str] inputs: list[InputConfig] servers: list[ServerConfig]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Utility functions for MCPClient and Tiny Agents.
Formatting utilities taken from the JS SDK: https://github.com/huggingface/huggingface.js/blob/main/packages/mcp-client/src/ResultFormatter.ts."""
import jsonfrom pathlib import Pathfrom typing import TYPE_CHECKING, Optional
from huggingface_hub import snapshot_downloadfrom huggingface_hub.errors import EntryNotFoundError
from .constants import DEFAULT_AGENT, DEFAULT_REPO_ID, FILENAME_CONFIG, PROMPT_FILENAMESfrom .types import AgentConfig
if TYPE_CHECKING: from mcp import types as mcp_types
def format_result(result: "mcp_types.CallToolResult") -> str: """ Formats a mcp.types.CallToolResult content into a human-readable string.
Args: result (CallToolResult) Object returned by mcp.ClientSession.call_tool.
Returns: str A formatted string representing the content of the result. """ content = result.content
if len(content) == 0: return "[No content]"
formatted_parts: list[str] = []
for item in content: match item.type: case "text": formatted_parts.append(item.text)
case "image": formatted_parts.append( f"[Binary Content: Image {item.mimeType}, {_get_base64_size(item.data)} bytes]\n" f"The task is complete and the content accessible to the User" )
case "audio": formatted_parts.append( f"[Binary Content: Audio {item.mimeType}, {_get_base64_size(item.data)} bytes]\n" f"The task is complete and the content accessible to the User" )
case "resource": resource = item.resource
if hasattr(resource, "text") and isinstance(resource.text, str): formatted_parts.append(resource.text)
elif hasattr(resource, "blob") and isinstance(resource.blob, str): formatted_parts.append( f"[Binary Content ({resource.uri}): {resource.mimeType}," f" {_get_base64_size(resource.blob)} bytes]\n" f"The task is complete and the content accessible to the User" )
return "\n".join(formatted_parts)
def _get_base64_size(base64_str: str) -> int: """Estimate the byte size of a base64-encoded string.""" # Remove any prefix like "data:image/png;base64," if "," in base64_str: base64_str = base64_str.split(",")[1]
padding = 0 if base64_str.endswith("=="): padding = 2 elif base64_str.endswith("="): padding = 1
return (len(base64_str) * 3) // 4 - padding
def _load_agent_config(agent_path: Optional[str]) -> tuple[AgentConfig, Optional[str]]: """Load server config and prompt."""
def _read_dir(directory: Path) -> tuple[AgentConfig, Optional[str]]: cfg_file = directory / FILENAME_CONFIG if not cfg_file.exists(): raise FileNotFoundError(f" Config file not found in {directory}! Please make sure it exists locally")
config: AgentConfig = json.loads(cfg_file.read_text(encoding="utf-8")) prompt: Optional[str] = None for filename in PROMPT_FILENAMES: prompt_file = directory / filename if prompt_file.exists(): prompt = prompt_file.read_text(encoding="utf-8") break return config, prompt
if agent_path is None: return DEFAULT_AGENT, None # type: ignore
path = Path(agent_path).expanduser()
if path.is_file(): return json.loads(path.read_text(encoding="utf-8")), None
if path.is_dir(): return _read_dir(path)
# fetch from the Hub try: repo_dir = Path( snapshot_download( repo_id=DEFAULT_REPO_ID, allow_patterns=f"{agent_path}/*", repo_type="dataset", ) ) return _read_dir(repo_dir / agent_path) except Exception as err: raise EntryNotFoundError( f" Agent {agent_path} not found in tiny-agents/tiny-agents! Please make sure it exists in https://huggingface.co/datasets/tiny-agents/tiny-agents." ) from err123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270from typing import Literal, Union
from huggingface_hub.inference._providers.featherless_ai import ( FeatherlessConversationalTask, FeatherlessTextGenerationTask,)from huggingface_hub.utils import logging
from ._common import AutoRouterConversationalTask, TaskProviderHelper, _fetch_inference_provider_mappingfrom .black_forest_labs import BlackForestLabsTextToImageTaskfrom .cerebras import CerebrasConversationalTaskfrom .clarifai import ClarifaiConversationalTaskfrom .cohere import CohereConversationalTaskfrom .fal_ai import ( FalAIAutomaticSpeechRecognitionTask, FalAIImageSegmentationTask, FalAIImageToImageTask, FalAIImageToVideoTask, FalAITextToImageTask, FalAITextToSpeechTask, FalAITextToVideoTask,)from .fireworks_ai import FireworksAIConversationalTaskfrom .groq import GroqConversationalTaskfrom .hf_inference import ( HFInferenceBinaryInputTask, HFInferenceConversational, HFInferenceFeatureExtractionTask, HFInferenceTask,)from .hyperbolic import HyperbolicTextGenerationTask, HyperbolicTextToImageTaskfrom .nebius import ( NebiusConversationalTask, NebiusFeatureExtractionTask, NebiusTextGenerationTask, NebiusTextToImageTask,)from .novita import NovitaConversationalTask, NovitaTextGenerationTask, NovitaTextToVideoTaskfrom .nscale import NscaleConversationalTask, NscaleTextToImageTaskfrom .nvidia import NvidiaConversationalTaskfrom .openai import OpenAIConversationalTaskfrom .ovhcloud import OVHcloudConversationalTaskfrom .publicai import PublicAIConversationalTaskfrom .replicate import ( ReplicateAutomaticSpeechRecognitionTask, ReplicateImageToImageTask, ReplicateTask, ReplicateTextToImageTask, ReplicateTextToSpeechTask,)from .sambanova import SambanovaConversationalTask, SambanovaFeatureExtractionTaskfrom .scaleway import ScalewayConversationalTask, ScalewayFeatureExtractionTaskfrom .together import TogetherConversationalTask, TogetherTextGenerationTask, TogetherTextToImageTaskfrom .wavespeed import ( WavespeedAIImageToImageTask, WavespeedAIImageToVideoTask, WavespeedAITextToImageTask, WavespeedAITextToVideoTask,)from .zai_org import ZaiConversationalTask, ZaiTextToImageTask
logger = logging.get_logger(__name__)
PROVIDER_T = Literal[ "black-forest-labs", "cerebras", "clarifai", "cohere", "fal-ai", "featherless-ai", "fireworks-ai", "groq", "hf-inference", "hyperbolic", "nebius", "novita", "nscale", "nvidia", "openai", "ovhcloud", "publicai", "replicate", "sambanova", "scaleway", "together", "wavespeed", "zai-org",]
PROVIDER_OR_POLICY_T = Union[PROVIDER_T, Literal["auto"]]
CONVERSATIONAL_AUTO_ROUTER = AutoRouterConversationalTask()
PROVIDERS: dict[PROVIDER_T, dict[str, TaskProviderHelper]] = { "black-forest-labs": { "text-to-image": BlackForestLabsTextToImageTask(), }, "cerebras": { "conversational": CerebrasConversationalTask(), }, "clarifai": { "conversational": ClarifaiConversationalTask(), }, "cohere": { "conversational": CohereConversationalTask(), }, "fal-ai": { "automatic-speech-recognition": FalAIAutomaticSpeechRecognitionTask(), "text-to-image": FalAITextToImageTask(), "text-to-speech": FalAITextToSpeechTask(), "text-to-video": FalAITextToVideoTask(), "image-to-video": FalAIImageToVideoTask(), "image-to-image": FalAIImageToImageTask(), "image-segmentation": FalAIImageSegmentationTask(), }, "featherless-ai": { "conversational": FeatherlessConversationalTask(), "text-generation": FeatherlessTextGenerationTask(), }, "fireworks-ai": { "conversational": FireworksAIConversationalTask(), }, "groq": { "conversational": GroqConversationalTask(), }, "hf-inference": { "text-to-image": HFInferenceTask("text-to-image"), "conversational": HFInferenceConversational(), "text-generation": HFInferenceTask("text-generation"), "text-classification": HFInferenceTask("text-classification"), "question-answering": HFInferenceTask("question-answering"), "audio-classification": HFInferenceBinaryInputTask("audio-classification"), "automatic-speech-recognition": HFInferenceBinaryInputTask("automatic-speech-recognition"), "fill-mask": HFInferenceTask("fill-mask"), "feature-extraction": HFInferenceFeatureExtractionTask(), "image-classification": HFInferenceBinaryInputTask("image-classification"), "image-segmentation": HFInferenceBinaryInputTask("image-segmentation"), "document-question-answering": HFInferenceTask("document-question-answering"), "image-to-text": HFInferenceBinaryInputTask("image-to-text"), "object-detection": HFInferenceBinaryInputTask("object-detection"), "audio-to-audio": HFInferenceBinaryInputTask("audio-to-audio"), "zero-shot-image-classification": HFInferenceBinaryInputTask("zero-shot-image-classification"), "zero-shot-classification": HFInferenceTask("zero-shot-classification"), "image-to-image": HFInferenceBinaryInputTask("image-to-image"), "sentence-similarity": HFInferenceTask("sentence-similarity"), "table-question-answering": HFInferenceTask("table-question-answering"), "tabular-classification": HFInferenceTask("tabular-classification"), "text-to-speech": HFInferenceTask("text-to-speech"), "token-classification": HFInferenceTask("token-classification"), "translation": HFInferenceTask("translation"), "summarization": HFInferenceTask("summarization"), "visual-question-answering": HFInferenceBinaryInputTask("visual-question-answering"), }, "hyperbolic": { "text-to-image": HyperbolicTextToImageTask(), "conversational": HyperbolicTextGenerationTask("conversational"), "text-generation": HyperbolicTextGenerationTask("text-generation"), }, "nebius": { "text-to-image": NebiusTextToImageTask(), "conversational": NebiusConversationalTask(), "text-generation": NebiusTextGenerationTask(), "feature-extraction": NebiusFeatureExtractionTask(), }, "novita": { "text-generation": NovitaTextGenerationTask(), "conversational": NovitaConversationalTask(), "text-to-video": NovitaTextToVideoTask(), }, "nscale": { "conversational": NscaleConversationalTask(), "text-to-image": NscaleTextToImageTask(), }, "nvidia": { "conversational": NvidiaConversationalTask(), }, "openai": { "conversational": OpenAIConversationalTask(), }, "ovhcloud": { "conversational": OVHcloudConversationalTask(), }, "publicai": { "conversational": PublicAIConversationalTask(), }, "replicate": { "automatic-speech-recognition": ReplicateAutomaticSpeechRecognitionTask(), "image-to-image": ReplicateImageToImageTask(), "text-to-image": ReplicateTextToImageTask(), "text-to-speech": ReplicateTextToSpeechTask(), "text-to-video": ReplicateTask("text-to-video"), }, "sambanova": { "conversational": SambanovaConversationalTask(), "feature-extraction": SambanovaFeatureExtractionTask(), }, "scaleway": { "conversational": ScalewayConversationalTask(), "feature-extraction": ScalewayFeatureExtractionTask(), }, "together": { "text-to-image": TogetherTextToImageTask(), "conversational": TogetherConversationalTask(), "text-generation": TogetherTextGenerationTask(), }, "wavespeed": { "text-to-image": WavespeedAITextToImageTask(), "text-to-video": WavespeedAITextToVideoTask(), "image-to-image": WavespeedAIImageToImageTask(), "image-to-video": WavespeedAIImageToVideoTask(), }, "zai-org": { "conversational": ZaiConversationalTask(), "text-to-image": ZaiTextToImageTask(), },}
def get_provider_helper(provider: PROVIDER_OR_POLICY_T | None, task: str, model: str | None) -> TaskProviderHelper: """Get provider helper instance by name and task.
Args: provider (`str`, *optional*): name of the provider, or "auto" to automatically select the provider for the model. task (`str`): Name of the task model (`str`, *optional*): Name of the model Returns: TaskProviderHelper: Helper instance for the specified provider and task
Raises: ValueError: If provider or task is not supported """
if (model is None and provider in (None, "auto")) or ( model is not None and model.startswith(("http://", "https://")) ): provider = "hf-inference"
if provider is None: logger.info( "No provider specified for task `conversational`. Defaulting to server-side auto routing." if task == "conversational" else "Defaulting to 'auto' which will select the first provider available for the model, sorted by the user's order in https://hf.co/settings/inference-providers." ) provider = "auto"
if provider == "auto": if model is None: raise ValueError("Specifying a model is required when provider is 'auto'") if task == "conversational": # Special case: we have a dedicated auto-router for conversational models. No need to fetch provider mapping. return CONVERSATIONAL_AUTO_ROUTER
provider_mapping = _fetch_inference_provider_mapping(model) provider = next(iter(provider_mapping)).provider
provider_tasks = PROVIDERS.get(provider) # type: ignore if provider_tasks is None: raise ValueError( f"Provider '{provider}' not supported. Available values: 'auto' or any provider from {list(PROVIDERS.keys())}." "Passing 'auto' (default value) will automatically select the first provider available for the model, sorted " "by the user's order in https://hf.co/settings/inference-providers." )
if task not in provider_tasks: raise ValueError( f"Task '{task}' not supported for provider '{provider}'. Available tasks: {list(provider_tasks.keys())}" ) return provider_tasks[task]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364from functools import lru_cachefrom typing import Any, overload
from huggingface_hub import constantsfrom huggingface_hub.hf_api import InferenceProviderMappingfrom huggingface_hub.inference._common import MimeBytes, RequestParametersfrom huggingface_hub.inference._generated.types.chat_completion import ChatCompletionInputMessagefrom huggingface_hub.utils import build_hf_headers, get_token, logging
logger = logging.get_logger(__name__)
# Dev purposes only.# If you want to try to run inference for a new model locally before it's registered on huggingface.co# for a given Inference Provider, you can add it to the following dictionary.HARDCODED_MODEL_INFERENCE_MAPPING: dict[str, dict[str, InferenceProviderMapping]] = { # "HF model ID" => InferenceProviderMapping object initialized with "Model ID on Inference Provider's side" # # Example: # "Qwen/Qwen2.5-Coder-32B-Instruct": InferenceProviderMapping(hf_model_id="Qwen/Qwen2.5-Coder-32B-Instruct", # provider_id="Qwen2.5-Coder-32B-Instruct", # task="conversational", # status="live") "cerebras": {}, "cohere": {}, "clarifai": {}, "fal-ai": {}, "fireworks-ai": {}, "groq": {}, "hf-inference": {}, "hyperbolic": {}, "nebius": {}, "nscale": {}, "nvidia": {}, "ovhcloud": {}, "replicate": {}, "sambanova": {}, "scaleway": {}, "together": {}, "wavespeed": {}, "zai-org": {},}
@overloaddef filter_none(obj: dict[str, Any]) -> dict[str, Any]: ...@overloaddef filter_none(obj: list[Any]) -> list[Any]: ...
def filter_none(obj: dict[str, Any] | list[Any]) -> dict[str, Any] | list[Any]: if isinstance(obj, dict): cleaned: dict[str, Any] = {} for k, v in obj.items(): if v is None: continue if isinstance(v, (dict, list)): v = filter_none(v) cleaned[k] = v return cleaned
if isinstance(obj, list): return [filter_none(v) if isinstance(v, (dict, list)) else v for v in obj]
raise ValueError(f"Expected dict or list, got {type(obj)}")
class TaskProviderHelper: """Base class for task-specific provider helpers."""
def __init__(self, provider: str, base_url: str, task: str) -> None: self.provider = provider self.task = task self.base_url = base_url
def prepare_request( self, *, inputs: Any, parameters: dict[str, Any], headers: dict, model: str | None, api_key: str | None, extra_payload: dict[str, Any] | None = None, ) -> RequestParameters: """ Prepare the request to be sent to the provider.
Each step (api_key, model, headers, url, payload) can be customized in subclasses. """ # api_key from user, or local token, or raise error api_key = self._prepare_api_key(api_key)
# mapped model from HF model ID provider_mapping_info = self._prepare_mapping_info(model)
# default HF headers + user headers (to customize in subclasses) headers = self._prepare_headers(headers, api_key)
# routed URL if HF token, or direct URL (to customize in '_prepare_route' in subclasses) url = self._prepare_url(api_key, provider_mapping_info.provider_id)
# prepare payload (to customize in subclasses) payload = self._prepare_payload_as_dict(inputs, parameters, provider_mapping_info=provider_mapping_info) if payload is not None: payload = recursive_merge(payload, filter_none(extra_payload or {}))
# body data (to customize in subclasses) data = self._prepare_payload_as_bytes(inputs, parameters, provider_mapping_info, extra_payload)
# check if both payload and data are set and return if payload is not None and data is not None: raise ValueError("Both payload and data cannot be set in the same request.") if payload is None and data is None: raise ValueError("Either payload or data must be set in the request.")
# normalize headers to lowercase and add content-type if not present normalized_headers = self._normalize_headers(headers, payload, data)
return RequestParameters( url=url, task=self.task, model=provider_mapping_info.provider_id, json=payload, data=data, headers=normalized_headers, )
def get_response( self, response: bytes | dict, request_params: RequestParameters | None = None, ) -> Any: """ Return the response in the expected format.
Override this method in subclasses for customized response handling.""" return response
def _prepare_api_key(self, api_key: str | None) -> str: """Return the API key to use for the request.
Usually not overwritten in subclasses.""" if api_key is None: api_key = get_token() if api_key is None: raise ValueError( f"You must provide an api_key to work with {self.provider} API or log in with `hf auth login`." ) return api_key
def _prepare_mapping_info(self, model: str | None) -> InferenceProviderMapping: """Return the mapped model ID to use for the request.
Usually not overwritten in subclasses.""" if model is None: raise ValueError(f"Please provide an HF model ID supported by {self.provider}.")
# hardcoded mapping for local testing if HARDCODED_MODEL_INFERENCE_MAPPING.get(self.provider, {}).get(model): return HARDCODED_MODEL_INFERENCE_MAPPING[self.provider][model]
provider_mapping = None for mapping in _fetch_inference_provider_mapping(model): if mapping.provider == self.provider: provider_mapping = mapping break
if provider_mapping is None: raise ValueError(f"Model {model} is not supported by provider {self.provider}.")
if provider_mapping.task != self.task: raise ValueError( f"Model {model} is not supported for task {self.task} and provider {self.provider}. " f"Supported task: {provider_mapping.task}." )
if provider_mapping.status == "staging": logger.warning( f"Model {model} is in staging mode for provider {self.provider}. Meant for test purposes only." ) if provider_mapping.status == "error": logger.warning( f"Our latest automated health check on model '{model}' for provider '{self.provider}' did not complete successfully. " "Inference call might fail." ) return provider_mapping
def _normalize_headers( self, headers: dict[str, Any], payload: dict[str, Any] | None, data: MimeBytes | None ) -> dict[str, Any]: """Normalize the headers to use for the request.
Override this method in subclasses for customized headers. """ normalized_headers = {key.lower(): value for key, value in headers.items() if value is not None} if normalized_headers.get("content-type") is None: if data is not None and data.mime_type is not None: normalized_headers["content-type"] = data.mime_type elif payload is not None: normalized_headers["content-type"] = "application/json" return normalized_headers
def _prepare_headers(self, headers: dict, api_key: str) -> dict[str, Any]: """Return the headers to use for the request.
Override this method in subclasses for customized headers. """ return {**build_hf_headers(token=api_key), **headers}
def _prepare_url(self, api_key: str, mapped_model: str) -> str: """Return the URL to use for the request.
Usually not overwritten in subclasses.""" base_url = self._prepare_base_url(api_key) route = self._prepare_route(mapped_model, api_key) return f"{base_url.rstrip('/')}/{route.lstrip('/')}"
def _prepare_base_url(self, api_key: str) -> str: """Return the base URL to use for the request.
Usually not overwritten in subclasses.""" # Route to the proxy if the api_key is a HF TOKEN if api_key.startswith("hf_"): logger.info(f"Calling '{self.provider}' provider through Hugging Face router.") return constants.INFERENCE_PROXY_TEMPLATE.format(provider=self.provider) else: logger.info(f"Calling '{self.provider}' provider directly.") return self.base_url
def _prepare_route(self, mapped_model: str, api_key: str) -> str: """Return the route to use for the request.
Override this method in subclasses for customized routes. """ return ""
def _prepare_payload_as_dict( self, inputs: Any, parameters: dict, provider_mapping_info: InferenceProviderMapping ) -> dict | None: """Return the payload to use for the request, as a dict.
Override this method in subclasses for customized payloads. Only one of `_prepare_payload_as_dict` and `_prepare_payload_as_bytes` should return a value. """ return None
def _prepare_payload_as_bytes( self, inputs: Any, parameters: dict, provider_mapping_info: InferenceProviderMapping, extra_payload: dict | None, ) -> MimeBytes | None: """Return the body to use for the request, as bytes.
Override this method in subclasses for customized body data. Only one of `_prepare_payload_as_dict` and `_prepare_payload_as_bytes` should return a value. """ return None
class BaseConversationalTask(TaskProviderHelper): """ Base class for conversational (chat completion) tasks. The schema follows the OpenAI API format defined here: https://platform.openai.com/docs/api-reference/chat """
def __init__(self, provider: str, base_url: str): super().__init__(provider=provider, base_url=base_url, task="conversational")
def _prepare_route(self, mapped_model: str, api_key: str) -> str: return "/v1/chat/completions"
def _prepare_payload_as_dict( self, inputs: list[dict | ChatCompletionInputMessage], parameters: dict, provider_mapping_info: InferenceProviderMapping, ) -> dict | None: return filter_none({"messages": inputs, **parameters, "model": provider_mapping_info.provider_id})
class AutoRouterConversationalTask(BaseConversationalTask): """ Auto-router for conversational tasks.
We let the Hugging Face router select the best provider for the model, based on availability and user preferences. This is a special case since the selection is done server-side (avoid 1 API call to fetch provider mapping). """
def __init__(self): super().__init__(provider="auto", base_url="https://router.huggingface.co")
def _prepare_base_url(self, api_key: str) -> str: """Return the base URL to use for the request.
Usually not overwritten in subclasses.""" # Route to the proxy if the api_key is a HF TOKEN if not api_key.startswith("hf_"): raise ValueError("Cannot select auto-router when using non-Hugging Face API key.") else: return self.base_url # No `/auto` suffix in the URL
def _prepare_mapping_info(self, model: str | None) -> InferenceProviderMapping: """ In auto-router, we don't need to fetch provider mapping info. We just return a dummy mapping info with provider_id set to the HF model ID. """ if model is None: raise ValueError("Please provide an HF model ID.")
return InferenceProviderMapping( provider="auto", hf_model_id=model, providerId=model, status="live", task="conversational", )
class BaseTextGenerationTask(TaskProviderHelper): """ Base class for text-generation (completion) tasks. The schema follows the OpenAI API format defined here: https://platform.openai.com/docs/api-reference/completions """
def __init__(self, provider: str, base_url: str): super().__init__(provider=provider, base_url=base_url, task="text-generation")
def _prepare_route(self, mapped_model: str, api_key: str) -> str: return "/v1/completions"
def _prepare_payload_as_dict( self, inputs: Any, parameters: dict, provider_mapping_info: InferenceProviderMapping ) -> dict | None: return filter_none({"prompt": inputs, **parameters, "model": provider_mapping_info.provider_id})
@lru_cache(maxsize=None)def _fetch_inference_provider_mapping(model: str) -> list["InferenceProviderMapping"]: """ Fetch provider mappings for a model from the Hub. """ from huggingface_hub.hf_api import HfApi
info = HfApi().model_info(model, expand=["inferenceProviderMapping"]) provider_mapping = info.inference_provider_mapping if provider_mapping is None: raise ValueError(f"No provider mapping found for model {model}") return provider_mapping
def recursive_merge(dict1: dict, dict2: dict) -> dict: return { **dict1, **{ key: recursive_merge(dict1[key], value) if (key in dict1 and isinstance(dict1[key], dict) and isinstance(value, dict)) else value for key, value in dict2.items() }, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import timefrom typing import Any
from huggingface_hub.hf_api import InferenceProviderMappingfrom huggingface_hub.inference._common import RequestParameters, _as_dictfrom huggingface_hub.inference._providers._common import TaskProviderHelper, filter_nonefrom huggingface_hub.utils import loggingfrom huggingface_hub.utils._http import get_session
logger = logging.get_logger(__name__)
MAX_POLLING_ATTEMPTS = 6POLLING_INTERVAL = 1.0
class BlackForestLabsTextToImageTask(TaskProviderHelper): def __init__(self): super().__init__(provider="black-forest-labs", base_url="https://api.us1.bfl.ai", task="text-to-image")
def _prepare_headers(self, headers: dict, api_key: str) -> dict[str, Any]: headers = super()._prepare_headers(headers, api_key) if not api_key.startswith("hf_"): _ = headers.pop("authorization") headers["X-Key"] = api_key return headers
def _prepare_route(self, mapped_model: str, api_key: str) -> str: return f"/v1/{mapped_model}"
def _prepare_payload_as_dict( self, inputs: Any, parameters: dict, provider_mapping_info: InferenceProviderMapping ) -> dict | None: parameters = filter_none(parameters) if "num_inference_steps" in parameters: parameters["steps"] = parameters.pop("num_inference_steps") if "guidance_scale" in parameters: parameters["guidance"] = parameters.pop("guidance_scale")
return {"prompt": inputs, **parameters}
def get_response(self, response: bytes | dict, request_params: RequestParameters | None = None) -> Any: """ Polling mechanism for Black Forest Labs since the API is asynchronous. """ url = _as_dict(response).get("polling_url") session = get_session() for _ in range(MAX_POLLING_ATTEMPTS): time.sleep(POLLING_INTERVAL)
response = session.get(url, headers={"Content-Type": "application/json"}) # type: ignore response.raise_for_status() # type: ignore response_json: dict = response.json() # type: ignore status = response_json.get("status") logger.info( f"Polling generation result from {url}. Current status: {status}. " f"Will retry after {POLLING_INTERVAL} seconds if not ready." )
if ( status == "Ready" and isinstance(response_json.get("result"), dict) and (sample_url := response_json["result"].get("sample")) ): image_resp = session.get(sample_url) image_resp.raise_for_status() return image_resp.content
raise TimeoutError(f"Failed to get the image URL after {MAX_POLLING_ATTEMPTS} attempts.")123456from ._common import BaseConversationalTask
class CerebrasConversationalTask(BaseConversationalTask): def __init__(self): super().__init__(provider="cerebras", base_url="https://api.cerebras.ai").cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/__init__.pyAdded
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/_async_client.pyAdded
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/__init__.pyAdded+204
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/audio_classification.pyAdded+43
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/audio_to_audio.pyAdded+30
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/automatic_speech_recognition.pyAdded+113
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/base.pyAdded+167
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/chat_completion.pyAdded+347
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/depth_estimation.pyAdded+28
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/document_question_answering.pyAdded+80
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/feature_extraction.pyAdded+36
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/fill_mask.pyAdded+47
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_classification.pyAdded+43
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_segmentation.pyAdded+51
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_text_to_image.pyAdded+67
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_text_to_video.pyAdded+65
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_to_image.pyAdded+60
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_to_text.pyAdded+100
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/image_to_video.pyAdded+60
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/object_detection.pyAdded+56
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/question_answering.pyAdded+72
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/sentence_similarity.pyAdded+27
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/summarization.pyAdded+41
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/table_question_answering.pyAdded+62
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text2text_generation.pyAdded+42
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_classification.pyAdded+41
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_generation.pyAdded+168
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_to_audio.pyAdded+99
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_to_image.pyAdded+50
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_to_speech.pyAdded+99
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/text_to_video.pyAdded+46
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/token_classification.pyAdded+51
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/translation.pyAdded+49
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/video_classification.pyAdded+45
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/visual_question_answering.pyAdded+49
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/zero_shot_classification.pyAdded+43
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/zero_shot_image_classification.pyAdded+38
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_generated/types/zero_shot_object_detection.pyAdded+50
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/__init__.pyAdded
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/_cli_hacks.pyAdded+88
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/agent.pyAdded+100
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/cli.pyAdded+255
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/constants.pyAdded+81
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/mcp_client.pyAdded+395
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/types.pyAdded+45
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_mcp/utils.pyAdded+130
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_providers/__init__.pyAdded+270
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_providers/_common.pyAdded+364
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_providers/black_forest_labs.pyAdded+69
.cache/uv/archive-v0/OUu0HPgppD7e5NOYzgGgo/huggingface_hub/inference/_providers/cerebras.pyAdded+6