Class HuggingFaceModel
java.lang.Object
uno.anahata.asi.agi.provider.AbstractModel
uno.anahata.asi.openai.compatible.OpenAiCompatibleModel
uno.anahata.asi.huggingface.HuggingFaceModel
A specialized model instance that encapsulates its own metadata discovery
from the Hugging Face Hub.
Fetches and parses architectural specifications (config.json), chat
templates and tokenizer settings (tokenizer_config.json), and
sampling parameters (generation_config.json) in parallel, enriching
generation requests with explicit max_tokens limits.
- Author:
- anahata
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate com.fasterxml.jackson.databind.JsonNodeThe raw JSON from the model's 'generation_config.json', used to extract default sampling parameters like temperature and top-p.private com.fasterxml.jackson.databind.JsonNodeThe raw JSON from the model's 'config.json', containing architectural details and token limits.private com.fasterxml.jackson.databind.JsonNodeThe raw JSON from the model's 'tokenizer_config.json', used to discover chat templates and tool support markers.Fields inherited from class AbstractModel
defaultTemperature, defaultTopK, defaultTopP, description, enabled, MARKUP_TABLE_HEADER, provider, rawDescription, supportedActions, supportedResponseModalities, tokenizerTypeModifier and TypeFieldDescriptionprotected FloatThe default temperature setting for this model, or null if unspecified.protected IntegerThe default Top-K setting for this model, or null if unspecified.protected FloatThe default Top-P setting for this model, or null if unspecified.protected StringHuman-readable description of this model's capabilities and limitations.protected booleanWhether this model is enabled and offered in model selectors and tool listings.static final StringMarkdown table header for model listings.protected AbstractAiProviderThe parent AI provider that owns this model instance.protected StringThe raw description or raw JSON representation of the model as received from the remote API endpoint.The list of API actions supported by this model (e.g.protected List<ResponseModality> The list of response modalities supported by this model (e.g., TEXT, IMAGE, AUDIO, VIDEO).protected TokenizerTypeThe optional model-specific tokenizer. -
Constructor Summary
ConstructorsConstructorDescriptionHuggingFaceModel(HuggingFaceProvider provider, String modelId, String displayName) Constructs a new Hugging Face model instance. -
Method Summary
Modifier and TypeMethodDescriptionBuilds a rich HTML view combining architecture, tokenizer class, and deep-inspected sampling parameters.protected voidenrichPayload(com.fasterxml.jackson.databind.node.ObjectNode payload, GenerationRequest request) Hook for subclasses to add or modify payload parameters before sending the request.private com.fasterxml.jackson.databind.JsonNodefetchHubJson(String filename, String apiKey) Helper to fetch a JSON file from the Hugging Face Hub's main branch.Returns the parentOpenAiChatCompletionsProviderinstance owning this model.voidPerforms deep inspection of this model by fetching its configuration files from the Hugging Face Hub sequentially in a single thread, using a pre-resolved API key.Methods inherited from class OpenAiCompatibleModel
buildParametersNode, countTokens, countTokens, countTokens, countTokens, createModelMessage, createResponseWithEstimatedUsage, generateContent, generateContentStream, getAvailableServerTools, getDefaultServerTools, getEndpoint, getToolDeclarationJson, isSupportsBatchEmbeddings, isSupportsCachedContent, isSupportsContentGeneration, isSupportsEmbeddings, isSupportsFunctionCalling, preparePayloadModifier and TypeMethodDescriptionprotected com.fasterxml.jackson.databind.node.ObjectNodebuildParametersNode(AbstractTool<?, ?> tool, boolean strict) Builds the JSON Schema parameters node for a tool.intcountTokens(byte[] data, String mimeType) Counts the number of tokens consumed by raw binary data based on its MIME type and model-specific multimodal billing rules.intcountTokens(String text) Counts the number of tokens in the given text string using this model's specific tokenizer.intcountTokens(AbstractToolCall<?, ?> toolCall) Counts the number of tokens consumed by the given tool call in the context window.intcountTokens(AbstractToolResponse<?> toolResponse) Counts the number of tokens consumed by the given tool execution response.createModelMessage(Agi agi) Instantiates an OpenAI-compatible message container.protected OpenAiCompatibleResponsecreateResponseWithEstimatedUsage(Agi agi, String modelId, String jsonPayload, String historyJson, int estimatedPromptTokens, int estimatedCompletionTokens, TokenizerType tokenizerType) Creates an OpenAiResponse with estimated usage metadata when the API doesn't provide it.generateContent(GenerationRequest request) The core method for interacting with an AI model.voidgenerateContentStream(GenerationRequest request, StreamObserver<Response<? extends AbstractModelMessage>> observer) Generates content asynchronously using token streaming.Gets the list of server-side tools available for this model.Gets the list of server-side tools that should be enabled by default for this model.protected StringGets the relative endpoint URL for Chat Completion requests.getToolDeclarationJson(AbstractTool<?, ?> tool, RequestConfig config) Gets the provider-specific JSON representation of a tool's declaration.booleanChecks if this model supports batch embedding generation.booleanChecks if this model supports content caching.booleanChecks if this model supports content generation.booleanChecks if this model supports single content embedding generation.booleanChecks if this model supports native function calling (tools).protected com.fasterxml.jackson.databind.node.ObjectNodepreparePayload(GenerationRequest request, boolean stream) Prepares the final JSON request payload combining system instructions, history, tools, and temperature.Methods inherited from class AbstractModel
getModelId, getProviderId, getTokenizerType, hasDiscrepancy, isRegistered, matches, persist, remove, resetFromApi, toMarkupRow, toSafeModelFileName, toStringModifier and TypeMethodDescriptionabstract StringGets the unique identifier for this model (e.g., "models/gemini-1.5-pro").final StringDelegate method to get the id of this models provider.Gets the effective tokenizer type for this model.booleanChecks if this locally registered model entity has different configuration values compared to its corresponding cached API model in the provider.booleanChecks if this model is registered in its parent provider's master persisted models list.booleanmatches(Pattern queryPattern, Set<ResponseModality> targetModalities) Checks if this model matches a search query (regex or substring) AND all target response modalities.voidpersist()Persists this model entity directly to disk in its parent provider's models directory (~/.anahata/asi/<provider>/models/<model_id>.kryo).voidremove()Deletes the persisted .kryo file for this model from disk and removes it from its parent provider.voidResets this locally registered model entity from its cached API model counterpart and persists changes to disk.Formats this model as a Markdown table row for model listing and discovery tools.static StringtoSafeModelFileName(String modelId) Converts a model ID into a safe filename with .kryo extension.toString()Returning the display name
-
Field Details
-
hubConfig
private com.fasterxml.jackson.databind.JsonNode hubConfigThe raw JSON from the model's 'config.json', containing architectural details and token limits. -
tokenizerConfig
private com.fasterxml.jackson.databind.JsonNode tokenizerConfigThe raw JSON from the model's 'tokenizer_config.json', used to discover chat templates and tool support markers. -
generationConfig
private com.fasterxml.jackson.databind.JsonNode generationConfigThe raw JSON from the model's 'generation_config.json', used to extract default sampling parameters like temperature and top-p.
-
-
Constructor Details
-
HuggingFaceModel
Constructs a new Hugging Face model instance.- Parameters:
provider- The owning HF provider.modelId- The full repo ID.displayName- The display name.
-
-
Method Details
-
getProvider
Returns the parentOpenAiChatCompletionsProviderinstance owning this model.Returns the typed parent
HuggingFaceProviderowning this model.- Overrides:
getProviderin classOpenAiCompatibleModel- Returns:
- The OpenAI-compatible provider instance.
-
inspect
Performs deep inspection of this model by fetching its configuration files from the Hugging Face Hub sequentially in a single thread, using a pre-resolved API key.- Parameters:
apiKey- The pre-resolved API key to avoid lock contention with the provider.
-
fetchHubJson
Helper to fetch a JSON file from the Hugging Face Hub's main branch.- Parameters:
filename- The config filename (e.g. 'config.json').apiKey- The pre-resolved Bearer token.- Returns:
- The parsed JSON or null if not found/error.
-
enrichPayload
protected void enrichPayload(com.fasterxml.jackson.databind.node.ObjectNode payload, GenerationRequest request) Hook for subclasses to add or modify payload parameters before sending the request.Implementation details: Ensures that
max_tokensis populated in the request payload so Hugging Face router does not truncate generations at its low server default.- Overrides:
enrichPayloadin classOpenAiCompatibleModel- Parameters:
payload- The JSON payload being constructed.request- The generation request.
-
buildHubHtmlDescription
Builds a rich HTML view combining architecture, tokenizer class, and deep-inspected sampling parameters.- Returns:
- The formatted HTML summary string.
-

