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