Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(hugging-face): let agents search the Hub, read repos and papers, and run chat and embeddings (#15793)

Odai Ahmadf39970f33b0f
diff --git a/bun.lock b/bun.lock
index 1486ea18d91..18c874d0cb8 100644
--- a/bun.lock
+++ b/bun.lock
@@ -4362,7 +4362,7 @@
},
"packages/pieces/community/hugging-face": {
"name": "@activepieces/piece-hugging-face",
- "version": "0.1.8",
+ "version": "0.2.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -4373,6 +4373,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/hume-ai": {
diff --git a/packages/pieces/community/hugging-face/package.json b/packages/pieces/community/hugging-face/package.json
index f0a51b89cb8..0b709e6b7a2 100644
--- a/packages/pieces/community/hugging-face/package.json
+++ b/packages/pieces/community/hugging-face/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-hugging-face",
- "version": "0.1.8",
+ "version": "0.2.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"dependencies": {
@@ -12,11 +12,13 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/hugging-face/src/i18n/translation.json b/packages/pieces/community/hugging-face/src/i18n/translation.json
index da34bce9c7d..b616da725ae 100644
--- a/packages/pieces/community/hugging-face/src/i18n/translation.json
+++ b/packages/pieces/community/hugging-face/src/i18n/translation.json
@@ -9,6 +9,35 @@
"Create Image": "Create Image",
"Object Detection": "Object Detection",
"Image Classification": "Image Classification",
+ "Search Models": "Search Models",
+ "Search Datasets": "Search Datasets",
+ "Search Spaces": "Search Spaces",
+ "Get Model": "Get Model",
+ "Get Dataset": "Get Dataset",
+ "Get Space": "Get Space",
+ "List Trending Repos": "List Trending Repos",
+ "List Hub Tags by Type": "List Hub Tags by Type",
+ "List Repo Files": "List Repo Files",
+ "Get File/Folder Info": "Get File/Folder Info",
+ "Read Repo File": "Read Repo File",
+ "List Repo Commits": "List Repo Commits",
+ "List Branches & Tags": "List Branches & Tags",
+ "Compare Revisions": "Compare Revisions",
+ "Get Repo Size": "Get Repo Size",
+ "Get Security Scan": "Get Security Scan",
+ "Get Current User & Token": "Get Current User & Token",
+ "Get User Profile": "Get User Profile",
+ "Get Organization Profile": "Get Organization Profile",
+ "List Organization Members": "List Organization Members",
+ "List Discussions & PRs": "List Discussions & PRs",
+ "Get Discussion or PR": "Get Discussion or PR",
+ "List Daily Papers": "List Daily Papers",
+ "Search Papers": "Search Papers",
+ "Get Paper": "Get Paper",
+ "List Collections": "List Collections",
+ "Get Collection": "Get Collection",
+ "Generate Chat Completion": "Generate Chat Completion",
+ "Generate Text Embeddings": "Generate Text Embeddings",
"Answer questions from document images using Hugging Face models": "Answer questions from document images using Hugging Face models",
"Translate text between languages using specialized Hugging Face translation models": "Translate text between languages using specialized Hugging Face translation models",
"Classify text into categories using Hugging Face models - includes zero-shot classification for custom categories": "Classify text into categories using Hugging Face models - includes zero-shot classification for custom categories",
@@ -17,6 +46,35 @@
"Generate stunning images from text prompts using state-of-the-art diffusion models - perfect for marketing, product design, and creative content": "Generate stunning images from text prompts using state-of-the-art diffusion models - perfect for marketing, product design, and creative content",
"Detect and locate objects in images with precise bounding boxes - perfect for inventory management, content moderation, and automated tagging": "Detect and locate objects in images with precise bounding boxes - perfect for inventory management, content moderation, and automated tagging",
"Classify images with pre-trained models or custom categories - perfect for content moderation, automated tagging, and smart asset management": "Classify images with pre-trained models or custom categories - perfect for content moderation, automated tagging, and smart asset management",
+ "Search and filter models on the Hugging Face Hub.": "Search and filter models on the Hugging Face Hub.",
+ "Search and filter datasets on the Hugging Face Hub.": "Search and filter datasets on the Hugging Face Hub.",
+ "Search and filter Spaces (hosted ML apps) on the Hugging Face Hub.": "Search and filter Spaces (hosted ML apps) on the Hugging Face Hub.",
+ "Get the Hub metadata of one model repository.": "Get the Hub metadata of one model repository.",
+ "Get the Hub metadata of one dataset repository.": "Get the Hub metadata of one dataset repository.",
+ "Get the Hub metadata of one Space.": "Get the Hub metadata of one Space.",
+ "List the repositories currently trending on the Hugging Face Hub.": "List the repositories currently trending on the Hugging Face Hub.",
+ "List the tags available for filtering models or datasets, grouped by tag type.": "List the tags available for filtering models or datasets, grouped by tag type.",
+ "List the files and folders of a model, dataset or Space repository.": "List the files and folders of a model, dataset or Space repository.",
+ "Get size, LFS and last-commit details for specific files or folders in a repository.": "Get size, LFS and last-commit details for specific files or folders in a repository.",
+ "Read a text file (such as README.md or config.json) from a Hub repository.": "Read a text file (such as README.md or config.json) from a Hub repository.",
+ "List the commit history of a branch or revision in a Hub repository.": "List the commit history of a branch or revision in a Hub repository.",
+ "List the branches, tags and converted refs of a Hub repository.": "List the branches, tags and converted refs of a Hub repository.",
+ "Get the git diff between two revisions of a Hub repository.": "Get the git diff between two revisions of a Hub repository.",
+ "Get the total size in bytes of a repository, or of one folder in it.": "Get the total size in bytes of a repository, or of one folder in it.",
+ "Get the malware and pickle security-scan status of a repository.": "Get the malware and pickle security-scan status of a repository.",
+ "Get the Hugging Face account behind the connection and the role of its access token.": "Get the Hugging Face account behind the connection and the role of its access token.",
+ "Get the public profile of a Hugging Face user.": "Get the public profile of a Hugging Face user.",
+ "Get the public profile of a Hugging Face organization.": "Get the public profile of a Hugging Face organization.",
+ "List the members of a Hugging Face organization.": "List the members of a Hugging Face organization.",
+ "List the discussions and pull requests of a Hub repository.": "List the discussions and pull requests of a Hub repository.",
+ "Get one discussion or pull request of a Hub repository, with its comments and events.": "Get one discussion or pull request of a Hub repository, with its comments and events.",
+ "List the research papers featured on Hugging Face's Daily Papers page.": "List the research papers featured on Hugging Face's Daily Papers page.",
+ "Search research papers indexed on Hugging Face.": "Search research papers indexed on Hugging Face.",
+ "Get the details of one research paper on Hugging Face.": "Get the details of one research paper on Hugging Face.",
+ "List or search curated collections on the Hugging Face Hub.": "List or search curated collections on the Hugging Face Hub.",
+ "Get one Hugging Face collection with all of its items.": "Get one Hugging Face collection with all of its items.",
+ "Generate an assistant reply from a list of chat messages with a model served by Inference Providers.": "Generate an assistant reply from a list of chat messages with a model served by Inference Providers.",
+ "Turn text into embedding vectors with a feature-extraction model served by Inference Providers.": "Turn text into embedding vectors with a feature-extraction model served by Inference Providers.",
"Model": "Model",
"Document Image": "Document Image",
"Question": "Question",
@@ -37,7 +95,6 @@
"Zero-Shot Model": "Zero-Shot Model",
"Custom Categories": "Custom Categories",
"Pre-trained Model": "Pre-trained Model",
- "Search Models": "Search Models",
"Text to Classify": "Text to Classify",
"Number of Results": "Number of Results",
"Output Function": "Output Function",
@@ -85,6 +142,61 @@
"Image File": "Image File",
"Image URL": "Image URL",
"Classification Template": "Classification Template",
+ "Search": "Search",
+ "Author": "Author",
+ "Tag Filters": "Tag Filters",
+ "Pipeline Task": "Pipeline Task",
+ "Inference Provider": "Inference Provider",
+ "Sort By": "Sort By",
+ "Limit": "Limit",
+ "Include Full Details": "Include Full Details",
+ "Cursor": "Cursor",
+ "Gated": "Gated",
+ "Repository ID": "Repository ID",
+ "Revision": "Revision",
+ "Repository Type": "Repository Type",
+ "Tag Type": "Tag Type",
+ "Folder Path": "Folder Path",
+ "Recursive": "Recursive",
+ "Include Last Commit": "Include Last Commit",
+ "Paths": "Paths",
+ "File Path": "File Path",
+ "Page": "Page",
+ "Include Pull Request Refs": "Include Pull Request Refs",
+ "Base Revision": "Base Revision",
+ "Head Revision": "Head Revision",
+ "Username": "Username",
+ "Organization": "Organization",
+ "Email": "Email",
+ "Kind": "Kind",
+ "Status": "Status",
+ "Discussion Number": "Discussion Number",
+ "Date": "Date",
+ "Week": "Week",
+ "Month": "Month",
+ "Submitter": "Submitter",
+ "Query": "Query",
+ "Paper ID": "Paper ID",
+ "Include Comments": "Include Comments",
+ "Include Submission Deadline": "Include Submission Deadline",
+ "Owner": "Owner",
+ "Contains Item": "Contains Item",
+ "Collection Slug": "Collection Slug",
+ "Provider": "Provider",
+ "Messages": "Messages",
+ "System Prompt": "System Prompt",
+ "Max Tokens": "Max Tokens",
+ "Temperature": "Temperature",
+ "Top P": "Top P",
+ "Stop Sequences": "Stop Sequences",
+ "Seed": "Seed",
+ "Response Format": "Response Format",
+ "JSON Schema": "JSON Schema",
+ "Texts": "Texts",
+ "Normalize": "Normalize",
+ "Truncate": "Truncate",
+ "Truncation Direction": "Truncation Direction",
+ "Prompt Name": "Prompt Name",
"Hugging Face document question answering model": "Hugging Face document question answering model",
"Image of the document to analyze (invoice, contract, etc.)": "Image of the document to analyze (invoice, contract, etc.)",
"Question to ask about the document (e.g., 'What is the invoice total?')": "Question to ask about the document (e.g., 'What is the invoice total?')",
@@ -163,6 +275,89 @@
"Maximum number of classification results to return (1-20)": "Maximum number of classification results to return (1-20)",
"Minimum confidence score for results (0.0-1.0)": "Minimum confidence score for results (0.0-1.0)",
"How to structure the classification results": "How to structure the classification results",
+ "Free-text match on the model ID, for example 'llama' or 'bert-base'.": "Free-text match on the model ID, for example 'llama' or 'bert-base'.",
+ "Only models owned by this user or organization, for example 'meta-llama'.": "Only models owned by this user or organization, for example 'meta-llama'.",
+ "Hub tags every result must carry, for example 'text-classification', 'pytorch', 'license:apache-2.0' or 'language:en'. Discover valid values with List Hub Tags by Type.": "Hub tags every result must carry, for example 'text-classification', 'pytorch', 'license:apache-2.0' or 'language:en'. Discover valid values with List Hub Tags by Type.",
+ "Only models for this task, for example 'text-generation', 'feature-extraction' or 'image-classification'.": "Only models for this task, for example 'text-generation', 'feature-extraction' or 'image-classification'.",
+ "Only models served by Inference Providers: 'all' for any provider, or one provider name such as 'groq', 'together' or 'hf-inference'.": "Only models served by Inference Providers: 'all' for any provider, or one provider name such as 'groq', 'together' or 'hf-inference'.",
+ "Sort order (always descending). Defaults to trending.": "Sort order (always descending). Defaults to trending.",
+ "Maximum number of results in this page (1 to 1000).": "Maximum number of results in this page (1 to 1000).",
+ "Return extra fields such as the file list and last-modified date for each model.": "Return extra fields such as the file list and last-modified date for each model.",
+ "The 'next_cursor' value returned by a previous call, to fetch the next page. Leave empty for the first page.": "The 'next_cursor' value returned by a previous call, to fetch the next page. Leave empty for the first page.",
+ "Free-text match on the dataset ID, for example 'imdb' or 'squad'.": "Free-text match on the dataset ID, for example 'imdb' or 'squad'.",
+ "Only datasets owned by this user or organization, for example 'stanfordnlp'.": "Only datasets owned by this user or organization, for example 'stanfordnlp'.",
+ "Hub tags every result must carry, for example 'task_categories:text-classification', 'language:en' or 'size_categories:10K<n<100K'. Discover valid values with List Hub Tags by Type.": "Hub tags every result must carry, for example 'task_categories:text-classification', 'language:en' or 'size_categories:10K<n<100K'. Discover valid values with List Hub Tags by Type.",
+ "Only gated datasets, only non-gated datasets, or leave empty for both.": "Only gated datasets, only non-gated datasets, or leave empty for both.",
+ "Return extra fields such as the card data and file list for each dataset.": "Return extra fields such as the card data and file list for each dataset.",
+ "Free-text match on the Space ID, for example 'whisper' or 'chatbot'.": "Free-text match on the Space ID, for example 'whisper' or 'chatbot'.",
+ "Only Spaces owned by this user or organization, for example 'huggingface'.": "Only Spaces owned by this user or organization, for example 'huggingface'.",
+ "Hub tags every result must carry, for example 'gradio', 'docker' or 'region:us'.": "Hub tags every result must carry, for example 'gradio', 'docker' or 'region:us'.",
+ "Return extra fields such as the card data and file list for each Space.": "Return extra fields such as the card data and file list for each Space.",
+ "The repository ID in 'namespace/name' form, for example 'openai-community/gpt2' or 'stanfordnlp/imdb'. Find it with Search Models, Search Datasets or Search Spaces.": "The repository ID in 'namespace/name' form, for example 'openai-community/gpt2' or 'stanfordnlp/imdb'. Find it with Search Models, Search Datasets or Search Spaces.",
+ "Optional branch, tag, or commit SHA, for example 'main' or 'refs/pr/1'. Leave empty for the default branch.": "Optional branch, tag, or commit SHA, for example 'main' or 'refs/pr/1'. Leave empty for the default branch.",
+ "Only trending repositories of this type. Defaults to all types.": "Only trending repositories of this type. Defaults to all types.",
+ "Number of trending repositories to return (1 to 20). Defaults to 10.": "Number of trending repositories to return (1 to 20). Defaults to 10.",
+ "Whose tags to list: 'model' or 'dataset'.": "Whose tags to list: 'model' or 'dataset'.",
+ "Only tags of this type. Models: pipeline_tag, library, dataset, language, license, arxiv, doi, region, deploy, other. Datasets: benchmark, task_categories, task_ids, size_categories, modality, format, library, language, license, arxiv, doi, region, annotations_creators, language_creators, multilinguality, source_datasets, other. Leave empty for every type (large).": "Only tags of this type. Models: pipeline_tag, library, dataset, language, license, arxiv, doi, region, deploy, other. Datasets: benchmark, task_categories, task_ids, size_categories, modality, format, library, language, license, arxiv, doi, region, annotations_creators, language_creators, multilinguality, source_datasets, other. Leave empty for every type (large).",
+ "The kind of Hub repository: 'model', 'dataset' or 'space'.": "The kind of Hub repository: 'model', 'dataset' or 'space'.",
+ "Branch, tag, or commit SHA to read, for example 'main', 'v1.0' or 'refs/pr/1'. Defaults to 'main'. List available refs with List Branches & Tags.": "Branch, tag, or commit SHA to read, for example 'main', 'v1.0' or 'refs/pr/1'. Defaults to 'main'. List available refs with List Branches & Tags.",
+ "Folder inside the repository to list, for example 'onnx' or 'data/train'. Leave empty for the root.": "Folder inside the repository to list, for example 'onnx' or 'data/train'. Leave empty for the root.",
+ "List every file in sub-folders too.": "List every file in sub-folders too.",
+ "Add the last commit and security-scan status to each entry. Limits a page to 100 entries.": "Add the last commit and security-scan status to each entry. Limits a page to 100 entries.",
+ "Maximum entries in this page: up to 1000, or up to 100 when Include Last Commit is on.": "Maximum entries in this page: up to 1000, or up to 100 when Include Last Commit is on.",
+ "File or folder paths inside the repository, for example 'config.json' or 'onnx/model.onnx'. Up to 2000.": "File or folder paths inside the repository, for example 'config.json' or 'onnx/model.onnx'. Up to 2000.",
+ "Add the last commit and security-scan status for each path.": "Add the last commit and security-scan status for each path.",
+ "Path of the file inside the repository, for example 'README.md' or 'configs/config.json'.": "Path of the file inside the repository, for example 'README.md' or 'configs/config.json'.",
+ "Zero-based page number. Use 0 for the first page, then the returned next_page value.": "Zero-based page number. Use 0 for the first page, then the returned next_page value.",
+ "Also list the 'refs/pr/N' refs of open and closed pull requests.": "Also list the 'refs/pr/N' refs of open and closed pull requests.",
+ "The older revision, for example 'main', 'v1.0' or a commit id.": "The older revision, for example 'main', 'v1.0' or a commit id.",
+ "The newer revision, for example 'refs/pr/1' or a commit id.": "The newer revision, for example 'refs/pr/1' or a commit id.",
+ "Folder to measure, for example 'onnx'. Leave empty for the whole repository.": "Folder to measure, for example 'onnx'. Leave empty for the whole repository.",
+ "The user's Hub username, for example 'julien-c'.": "The user's Hub username, for example 'julien-c'.",
+ "The organization's Hub name, for example 'huggingface' or 'meta-llama'.": "The organization's Hub name, for example 'huggingface' or 'meta-llama'.",
+ "The organization's Hub name, for example 'huggingface'.": "The organization's Hub name, for example 'huggingface'.",
+ "Only members whose username or full name matches this text.": "Only members whose username or full name matches this text.",
+ "Only the member with this email address. Organization admins only.": "Only the member with this email address. Organization admins only.",
+ "Maximum number of results in this page (1 to 10000).": "Maximum number of results in this page (1 to 10000).",
+ "Only discussions, only pull requests, or both. Defaults to both.": "Only discussions, only pull requests, or both. Defaults to both.",
+ "Only open, only closed, or both. Defaults to both.": "Only open, only closed, or both. Defaults to both.",
+ "Only threads opened by this Hub username, for example 'julien-c'.": "Only threads opened by this Hub username, for example 'julien-c'.",
+ "Only threads whose title matches this text.": "Only threads whose title matches this text.",
+ "Sort order. Defaults to most recently created.": "Sort order. Defaults to most recently created.",
+ "The discussion or pull request number within the repository, for example 12 (the 'num' from List Discussions & PRs).": "The discussion or pull request number within the repository, for example 12 (the 'num' from List Discussions & PRs).",
+ "Papers featured on this day, in 'YYYY-MM-DD' form, for example '2026-09-22'.": "Papers featured on this day, in 'YYYY-MM-DD' form, for example '2026-09-22'.",
+ "Papers featured in this ISO week, in 'YYYY-Www' form, for example '2026-W38'.": "Papers featured in this ISO week, in 'YYYY-Www' form, for example '2026-W38'.",
+ "Papers featured in this month, in 'YYYY-MM' form, for example '2026-09'.": "Papers featured in this month, in 'YYYY-MM' form, for example '2026-09'.",
+ "Only papers submitted by this Hub username.": "Only papers submitted by this Hub username.",
+ "Sort order. Defaults to publish date.": "Sort order. Defaults to publish date.",
+ "Maximum number of results in this page (1 to 100).": "Maximum number of results in this page (1 to 100).",
+ "What to search for, up to 250 characters, for example 'retrieval augmented generation'.": "What to search for, up to 250 characters, for example 'retrieval augmented generation'.",
+ "Maximum number of results in this page (1 to 120).": "Maximum number of results in this page (1 to 120).",
+ "The paper's arXiv ID, for example '2307.09288'.": "The paper's arXiv ID, for example '2307.09288'.",
+ "Also return the comments on the paper page, with their comment IDs.": "Also return the comments on the paper page, with their comment IDs.",
+ "Also return the conference submission deadline linked to the paper, when there is one.": "Also return the conference submission deadline linked to the paper, when there is one.",
+ "Only collections owned by this user or organization, for example 'huggingface'.": "Only collections owned by this user or organization, for example 'huggingface'.",
+ "Only collections that contain this item, written as '<type>/<id>', for example 'models/openai-community/gpt2', 'datasets/stanfordnlp/imdb' or 'papers/2307.09288'.": "Only collections that contain this item, written as '<type>/<id>', for example 'models/openai-community/gpt2', 'datasets/stanfordnlp/imdb' or 'papers/2307.09288'.",
+ "Only collections whose title matches this text.": "Only collections whose title matches this text.",
+ "Sort order. Defaults to trending.": "Sort order. Defaults to trending.",
+ "The full collection slug in 'namespace/title-id' form, for example 'meta-llama/llama-32-66f448ffc8c32f949b04c8cf' (the part after huggingface.co/collections/).": "The full collection slug in 'namespace/title-id' form, for example 'meta-llama/llama-32-66f448ffc8c32f949b04c8cf' (the part after huggingface.co/collections/).",
+ "Model ID served by Inference Providers, for example 'openai/gpt-oss-20b' or 'Qwen/Qwen3-8B'. Find others with Search Models (pipeline_tag 'text-generation', inference_provider 'all'); append ':<provider>' (for example ':groq') or ':preferred' to pick the provider. Leave empty to use openai/gpt-oss-20b.": "Model ID served by Inference Providers, for example 'openai/gpt-oss-20b' or 'Qwen/Qwen3-8B'. Find others with Search Models (pipeline_tag 'text-generation', inference_provider 'all'); append ':<provider>' (for example ':groq') or ':preferred' to pick the provider. Leave empty to use openai/gpt-oss-20b.",
+ "Inference provider to run the model on. Leave empty (or 'auto') to use the first available provider in your Hugging Face provider preference order.": "Inference provider to run the model on. Leave empty (or 'auto') to use the first available provider in your Hugging Face provider preference order.",
+ "The conversation as a JSON array of {\"role\", \"content\"} objects, oldest first, for example [{\"role\": \"user\", \"content\": \"Summarize this in one line: ...\"}]. Roles are system, user and assistant. For vision models, content may be an array of parts such as {\"type\": \"text\", \"text\": \"...\"} and {\"type\": \"image_url\", \"image_url\": {\"url\": \"https://...\"}}.": "The conversation as a JSON array of {\"role\", \"content\"} objects, oldest first, for example [{\"role\": \"user\", \"content\": \"Summarize this in one line: ...\"}]. Roles are system, user and assistant. For vision models, content may be an array of parts such as {\"type\": \"text\", \"text\": \"...\"} and {\"type\": \"image_url\", \"image_url\": {\"url\": \"https://...\"}}.",
+ "Optional instructions sent as a leading system message. Nothing is added when empty.": "Optional instructions sent as a leading system message. Nothing is added when empty.",
+ "Maximum number of tokens to generate in the reply, for example 512. Reasoning models such as openai/gpt-oss-20b spend part of this on hidden reasoning, so an empty reply with finish_reason 'length' means you should raise it to a few hundred or more.": "Maximum number of tokens to generate in the reply, for example 512. Reasoning models such as openai/gpt-oss-20b spend part of this on hidden reasoning, so an empty reply with finish_reason 'length' means you should raise it to a few hundred or more.",
+ "Sampling temperature between 0 and 2. 0 is the most deterministic. Leave empty for the model default.": "Sampling temperature between 0 and 2. 0 is the most deterministic. Leave empty for the model default.",
+ "Nucleus sampling probability mass between 0 and 1, for example 0.9. Leave empty for the model default.": "Nucleus sampling probability mass between 0 and 1, for example 0.9. Leave empty for the model default.",
+ "Up to 4 text sequences at which generation stops.": "Up to 4 text sequences at which generation stops.",
+ "Random seed for more repeatable sampling, where the provider supports it.": "Random seed for more repeatable sampling, where the provider supports it.",
+ "'json_object' forces valid JSON; 'json_schema' forces JSON matching the JSON Schema field. Defaults to plain text.": "'json_object' forces valid JSON; 'json_schema' forces JSON matching the JSON Schema field. Defaults to plain text.",
+ "Required when Response Format is json_schema: {\"name\": \"answer\", \"schema\": {...JSON Schema...}, \"strict\": true}. A bare JSON Schema object is also accepted.": "Required when Response Format is json_schema: {\"name\": \"answer\", \"schema\": {...JSON Schema...}, \"strict\": true}. A bare JSON Schema object is also accepted.",
+ "Feature-extraction model ID, for example 'BAAI/bge-small-en-v1.5' (384 dimensions) or 'intfloat/multilingual-e5-large'. Find others with Search Models (pipeline_tag 'feature-extraction', inference_provider 'all'); append ':<provider>' to pick the provider.": "Feature-extraction model ID, for example 'BAAI/bge-small-en-v1.5' (384 dimensions) or 'intfloat/multilingual-e5-large'. Find others with Search Models (pipeline_tag 'feature-extraction', inference_provider 'all'); append ':<provider>' to pick the provider.",
+ "The texts to embed. One text returns one embedding; several texts return one embedding each, in order.": "The texts to embed. One text returns one embedding; several texts return one embedding each, in order.",
+ "Scale each vector to unit length. Leave empty for the model default.": "Scale each vector to unit length. Leave empty for the model default.",
+ "Cut texts longer than the model's maximum input length instead of failing. Leave empty for the model default.": "Cut texts longer than the model's maximum input length instead of failing. Leave empty for the model default.",
+ "Which end of an over-long text to cut when truncating. Leave empty for the model default (right).": "Which end of an over-long text to cut when truncating. Leave empty for the model default (right).",
+ "Name of a prompt template defined in the model's Sentence Transformers config, for example 'query' or 'passage' for retrieval models. Leave empty when the model has none.": "Name of a prompt template defined in the model's Sentence Transformers config, for example 'query' or 'passage' for retrieval models. Leave empty when the model has none.",
"impira/layoutlm-document-qa (Recommended)": "impira/layoutlm-document-qa (Recommended)",
"microsoft/layoutlmv3-base": "microsoft/layoutlmv3-base",
"nielsr/layoutlmv2-finetuned-docvqa": "nielsr/layoutlmv2-finetuned-docvqa",
@@ -260,5 +455,50 @@
"💼 Business & Commerce": "💼 Business & Commerce",
"📎 Upload File": "📎 Upload File",
"🔗 Image URL": "🔗 Image URL",
- "🌐 Comprehensive Report": "🌐 Comprehensive Report"
+ "🌐 Comprehensive Report": "🌐 Comprehensive Report",
+ "Trending": "Trending",
+ "Downloads": "Downloads",
+ "Likes": "Likes",
+ "Recently Created": "Recently Created",
+ "Recently Updated": "Recently Updated",
+ "Only gated": "Only gated",
+ "Only not gated": "Only not gated",
+ "All": "All",
+ "Models": "Models",
+ "Datasets": "Datasets",
+ "Spaces": "Spaces",
+ "Dataset": "Dataset",
+ "Space": "Space",
+ "Discussions": "Discussions",
+ "Pull Requests": "Pull Requests",
+ "Open": "Open",
+ "Closed": "Closed",
+ "Most Reactions": "Most Reactions",
+ "Publish Date": "Publish Date",
+ "Upvotes": "Upvotes",
+ "black-forest-labs": "black-forest-labs",
+ "cerebras": "cerebras",
+ "cohere": "cohere",
+ "fal-ai": "fal-ai",
+ "featherless-ai": "featherless-ai",
+ "fireworks-ai": "fireworks-ai",
+ "groq": "groq",
+ "hf-inference": "hf-inference",
+ "hyperbolic": "hyperbolic",
+ "nebius": "nebius",
+ "novita": "novita",
+ "nscale": "nscale",
+ "openai": "openai",
+ "ovhcloud": "ovhcloud",
+ "replicate": "replicate",
+ "sambanova": "sambanova",
+ "scaleway": "scaleway",
+ "together": "together",
+ "Auto (your preference order)": "Auto (your preference order)",
+ "Text": "Text",
+ "JSON Object": "JSON Object",
+ "Yes": "Yes",
+ "No": "No",
+ "Right (keep the start)": "Right (keep the start)",
+ "Left (keep the end)": "Left (keep the end)"
}
\ No newline at end of file
diff --git a/packages/pieces/community/hugging-face/src/index.ts b/packages/pieces/community/hugging-face/src/index.ts
index d9bc98fa176..ce7e6b4cbe0 100644
--- a/packages/pieces/community/hugging-face/src/index.ts
+++ b/packages/pieces/community/hugging-face/src/index.ts
@@ -1,4 +1,4 @@
-import { createPiece, PieceAuth } from '@activepieces/pieces-framework';
+import { createPiece } from '@activepieces/pieces-framework';
import { PieceCategory } from '@activepieces/pieces-framework';
import { documentQuestionAnswering } from './lib/actions/document-question-answering';
import { languageTranslation } from './lib/actions/language-translation';
@@ -8,6 +8,35 @@ import { chatCompletion } from './lib/actions/chat-completion';
import { createImage } from './lib/actions/create-image';
import { objectDetection } from './lib/actions/object-detection';
import { imageClassification } from './lib/actions/image-classification';
+import { searchModels } from './lib/actions/search-models';
+import { searchDatasets } from './lib/actions/search-datasets';
+import { searchSpaces } from './lib/actions/search-spaces';
+import { getModel } from './lib/actions/get-model';
+import { getDataset } from './lib/actions/get-dataset';
+import { getSpace } from './lib/actions/get-space';
+import { listTrendingRepos } from './lib/actions/list-trending-repos';
+import { listHubTags } from './lib/actions/list-hub-tags';
+import { listRepoFiles } from './lib/actions/list-repo-files';
+import { getRepoPathsInfo } from './lib/actions/get-repo-paths-info';
+import { readRepoFile } from './lib/actions/read-repo-file';
+import { listRepoCommits } from './lib/actions/list-repo-commits';
+import { listRepoRefs } from './lib/actions/list-repo-refs';
+import { compareRepoRevisions } from './lib/actions/compare-repo-revisions';
+import { getRepoSize } from './lib/actions/get-repo-size';
+import { getRepoSecurityScan } from './lib/actions/get-repo-security-scan';
+import { getCurrentUser } from './lib/actions/get-current-user';
+import { getUserOverview } from './lib/actions/get-user-overview';
+import { getOrganizationOverview } from './lib/actions/get-organization-overview';
+import { listOrganizationMembers } from './lib/actions/list-organization-members';
+import { listDiscussions } from './lib/actions/list-discussions';
+import { getDiscussion } from './lib/actions/get-discussion';
+import { listDailyPapers } from './lib/actions/list-daily-papers';
+import { searchPapers } from './lib/actions/search-papers';
+import { getPaper } from './lib/actions/get-paper';
+import { listCollections } from './lib/actions/list-collections';
+import { getCollection } from './lib/actions/get-collection';
+import { generateChatCompletion } from './lib/actions/generate-chat-completion';
+import { generateEmbeddings } from './lib/actions/generate-embeddings';
import { huggingFaceAuth } from './lib/auth';
export const huggingface = createPiece({
@@ -15,7 +44,7 @@ export const huggingface = createPiece({
description:
'Run inference on 100,000+ open ML models for NLP, vision, and audio tasks',
auth: huggingFaceAuth,
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.87.0',
logoUrl: 'https://cdn.activepieces.com/pieces/huggingface.svg',
categories: [PieceCategory.ARTIFICIAL_INTELLIGENCE],
authors: ['Ani-4x'],
@@ -28,6 +57,35 @@ export const huggingface = createPiece({
createImage,
objectDetection,
imageClassification,
+ searchModels,
+ searchDatasets,
+ searchSpaces,
+ getModel,
+ getDataset,
+ getSpace,
+ listTrendingRepos,
+ listHubTags,
+ listRepoFiles,
+ getRepoPathsInfo,
+ readRepoFile,
+ listRepoCommits,
+ listRepoRefs,
+ compareRepoRevisions,
+ getRepoSize,
+ getRepoSecurityScan,
+ getCurrentUser,
+ getUserOverview,
+ getOrganizationOverview,
+ listOrganizationMembers,
+ listDiscussions,
+ getDiscussion,
+ listDailyPapers,
+ searchPapers,
+ getPaper,
+ listCollections,
+ getCollection,
+ generateChatCompletion,
+ generateEmbeddings,
],
triggers: [],
});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/chat-completion.ts b/packages/pieces/community/hugging-face/src/lib/actions/chat-completion.ts
index 0d1d962f298..cd2fdea852b 100644
--- a/packages/pieces/community/hugging-face/src/lib/actions/chat-completion.ts
+++ b/packages/pieces/community/hugging-face/src/lib/actions/chat-completion.ts
@@ -6,7 +6,7 @@ import { huggingFaceAuth } from '../auth';
import { chatCompletionOutputSchema } from '../output-schemas';
export const chatCompletion = createAction({
- audience: 'both',
+ audience: 'human',
name: 'chat_completion',
classification: 'READ',
auth: huggingFaceAuth,
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/compare-repo-revisions.ts b/packages/pieces/community/hugging-face/src/lib/actions/compare-repo-revisions.ts
new file mode 100644
index 00000000000..ea36c061c41
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/compare-repo-revisions.ts
@@ -0,0 +1,58 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { hfUtils } from '../common/utils';
+import { compareRepoRevisionsOutputSchema } from '../output-schemas';
+
+const MAX_DIFF_CHARS = 100000;
+
+export const compareRepoRevisions = createAction({
+ auth: huggingFaceAuth,
+ name: 'compare_repo_revisions',
+ classification: 'READ',
+ displayName: 'Compare Revisions',
+ description: 'Get the git diff between two revisions of a Hub repository.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns the raw git diff between two revisions (branches, tags or commit ids) of a Hub repository, for example to see what a pull request ref changes against main. The diff is cut at 100000 characters and truncated is set when that happens; large binary or LFS changes appear only as pointer changes. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: compareRepoRevisionsOutputSchema,
+ props: {
+ repo_type: hfProps.repoType(),
+ repo_id: hfProps.repoId(),
+ base: Property.ShortText({
+ displayName: 'Base Revision',
+ description: "The older revision, for example 'main', 'v1.0' or a commit id.",
+ required: true,
+ }),
+ head: Property.ShortText({
+ displayName: 'Head Revision',
+ description: "The newer revision, for example 'refs/pr/1' or a commit id.",
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { repo_type, repo_id, base, head } = context.propsValue;
+ const token = context.auth.secret_text;
+ const apiPath = await hfRepo.apiPath({ token, repoType: repo_type, repoId: repo_id });
+ const response = await hfHub.request<unknown>({
+ token,
+ method: HttpMethod.GET,
+ path: `${apiPath}/compare/${hfRepo.encodeRevision(base)}..${hfRepo.encodeRevision(head)}`,
+ });
+ const raw = typeof response.body === 'string' ? response.body : JSON.stringify(response.body ?? '');
+ const diff = hfUtils.truncateText({ text: raw, maxChars: MAX_DIFF_CHARS });
+ return {
+ base,
+ head,
+ diff: diff.text,
+ truncated: diff.truncated,
+ diff_length: diff.originalLength,
+ };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/document-question-answering.ts b/packages/pieces/community/hugging-face/src/lib/actions/document-question-answering.ts
index 05fae34970b..50fd8cc703e 100644
--- a/packages/pieces/community/hugging-face/src/lib/actions/document-question-answering.ts
+++ b/packages/pieces/community/hugging-face/src/lib/actions/document-question-answering.ts
@@ -15,7 +15,7 @@ export const documentQuestionAnswering = createAction({
'Answer questions from document images using Hugging Face models',
aiMetadata: {
description:
- 'Answers a natural-language question about an uploaded document image (invoice, contract, form) with a layout-aware extractive model such as LayoutLM, returning the matching text span and its confidence score. Choose it to pull one specific value out of a scanned document - use image_classification or object_detection for general-purpose vision, and chat_completion when the source text is already plain. Requires both a document image file and a question; read-only and idempotent, since it only analyses the supplied file.',
+ 'Answers a natural-language question about an uploaded document image (invoice, contract, form) with a layout-aware extractive model such as LayoutLM, returning the matching text span and its confidence score. Choose it to pull one specific value out of a scanned document - use image_classification or object_detection for general-purpose vision, and generate_chat_completion when the source text is already plain. Requires both a document image file and a question; read-only and idempotent, since it only analyses the supplied file.',
idempotent: true,
},
props: {
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/generate-chat-completion.ts b/packages/pieces/community/hugging-face/src/lib/actions/generate-chat-completion.ts
new file mode 100644
index 00000000000..34a2f6bd196
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/generate-chat-completion.ts
@@ -0,0 +1,241 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { InferenceClient } from '@huggingface/inference';
+import type { ChatCompletionInput, ChatCompletionInputMessage } from '@huggingface/tasks';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfInference } from '../common/inference';
+import { hfUtils } from '../common/utils';
+import { generateChatCompletionOutputSchema } from '../output-schemas';
+
+const DEFAULT_CHAT_MODEL = 'openai/gpt-oss-20b';
+
+export const generateChatCompletion = createAction({
+ auth: huggingFaceAuth,
+ name: 'generate_chat_completion',
+ classification: 'READ',
+ displayName: 'Generate Chat Completion',
+ description: 'Generate an assistant reply from a list of chat messages with a model served by Inference Providers.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Runs one OpenAI-style chat completion on a Hugging Face model served by Inference Providers and returns the assistant reply, finish reason and token usage. Use it for open-ended generation, reasoning or structured JSON output (set Response Format); prefer text_summarization, language_translation or text_classification for those narrower tasks. Reasoning models such as openai/gpt-oss-20b spend part of max_tokens on hidden reasoning, so an empty content with finish_reason 'length' means max_tokens must be raised to a few hundred or more. Each call spends the account's Inference Providers credits (free monthly allowance, then pay-as-you-go) and sampled output varies between runs, so it is not idempotent.",
+ idempotent: false,
+ },
+ outputSchema: generateChatCompletionOutputSchema,
+ props: {
+ model: Property.ShortText({
+ displayName: 'Model',
+ description:
+ "Model ID served by Inference Providers, for example 'openai/gpt-oss-20b' or 'Qwen/Qwen3-8B'. Find others with Search Models (pipeline_tag 'text-generation', inference_provider 'all'); append ':<provider>' (for example ':groq') or ':preferred' to pick the provider. Leave empty to use openai/gpt-oss-20b.",
+ required: false,
+ defaultValue: DEFAULT_CHAT_MODEL,
+ }),
+ provider: hfInference.providerProp(),
+ messages: Property.Json({
+ displayName: 'Messages',
+ description:
+ 'The conversation as a JSON array of {"role", "content"} objects, oldest first, for example [{"role": "user", "content": "Summarize this in one line: ..."}]. Roles are system, user and assistant. For vision models, content may be an array of parts such as {"type": "text", "text": "..."} and {"type": "image_url", "image_url": {"url": "https://..."}}.',
+ required: true,
+ }),
+ system_prompt: Property.LongText({
+ displayName: 'System Prompt',
+ description: 'Optional instructions sent as a leading system message. Nothing is added when empty.',
+ required: false,
+ }),
+ max_tokens: Property.Number({
+ displayName: 'Max Tokens',
+ description:
+ "Maximum number of tokens to generate in the reply, for example 512. Reasoning models such as openai/gpt-oss-20b spend part of this on hidden reasoning, so an empty reply with finish_reason 'length' means you should raise it to a few hundred or more.",
+ required: false,
+ }),
+ temperature: Property.Number({
+ displayName: 'Temperature',
+ description: 'Sampling temperature between 0 and 2. 0 is the most deterministic. Leave empty for the model default.',
+ required: false,
+ }),
+ top_p: Property.Number({
+ displayName: 'Top P',
+ description: 'Nucleus sampling probability mass between 0 and 1, for example 0.9. Leave empty for the model default.',
+ required: false,
+ }),
+ stop: Property.Array({
+ displayName: 'Stop Sequences',
+ description: 'Up to 4 text sequences at which generation stops.',
+ required: false,
+ }),
+ seed: Property.Number({
+ displayName: 'Seed',
+ description: 'Random seed for more repeatable sampling, where the provider supports it.',
+ required: false,
+ }),
+ response_format: Property.StaticDropdown({
+ displayName: 'Response Format',
+ description: "'json_object' forces valid JSON; 'json_schema' forces JSON matching the JSON Schema field. Defaults to plain text.",
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Text', value: 'text' },
+ { label: 'JSON Object', value: 'json_object' },
+ { label: 'JSON Schema', value: 'json_schema' },
+ ],
+ },
+ }),
+ json_schema: Property.Json({
+ displayName: 'JSON Schema',
+ description:
+ 'Required when Response Format is json_schema: {"name": "answer", "schema": {...JSON Schema...}, "strict": true}. A bare JSON Schema object is also accepted.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const {
+ model,
+ provider,
+ messages,
+ system_prompt,
+ max_tokens,
+ temperature,
+ top_p,
+ stop,
+ seed,
+ response_format,
+ json_schema,
+ } = context.propsValue;
+ const resolved = hfInference.resolveModelAndProvider({ model, provider, defaultModel: DEFAULT_CHAT_MODEL });
+ const conversation = parseMessages(messages);
+ const systemText = system_prompt?.trim();
+ const allMessages: ChatCompletionInputMessage[] = systemText
+ ? [{ role: 'system', content: systemText }, ...conversation]
+ : conversation;
+ const stopSequences = hfUtils.toStringArray(stop);
+ if (stopSequences.length > 4) {
+ throw new Error('Provide at most 4 stop sequences.');
+ }
+ const args: ChatCompletionInput = {
+ model: resolved.model,
+ messages: allMessages,
+ stream: false,
+ ...(max_tokens !== undefined ? { max_tokens } : {}),
+ ...(temperature !== undefined ? { temperature } : {}),
+ ...(top_p !== undefined ? { top_p } : {}),
+ ...(seed !== undefined ? { seed } : {}),
+ ...(stopSequences.length > 0 ? { stop: stopSequences } : {}),
+ ...buildResponseFormat({ format: response_format, schema: json_schema }),
+ };
+ const client = new InferenceClient(context.auth.secret_text);
+ try {
+ const result = await client.chatCompletion({ ...args, provider: resolved.provider });
+ const choice = result.choices?.[0];
+ return {
+ content: choice?.message?.content ?? null,
+ finish_reason: choice?.finish_reason ?? null,
+ model: result.model ?? resolved.model,
+ id: result.id ?? null,
+ usage: {
+ prompt_tokens: result.usage?.prompt_tokens ?? null,
+ completion_tokens: result.usage?.completion_tokens ?? null,
+ total_tokens: result.usage?.total_tokens ?? null,
+ },
+ };
+ } catch (error) {
+ throw hfInference.toError(error);
+ }
+ },
+});
+
+function parseMessages(value: unknown): ChatCompletionInputMessage[] {
+ const raw: unknown = typeof value === 'string' ? parseJson(value) : value;
+ if (!Array.isArray(raw) || raw.length === 0) {
+ throw new Error('Messages must be a non-empty JSON array of {"role", "content"} objects.');
+ }
+ return raw.map((item: unknown, index) => {
+ if (!hfHub.isRecord(item) || typeof item['role'] !== 'string') {
+ throw new Error(`Message ${index + 1} must be an object with a string "role".`);
+ }
+ const role = item['role'];
+ const content = item['content'];
+ if (typeof content === 'string') {
+ return { role, content };
+ }
+ if (Array.isArray(content)) {
+ return { role, content: content.map((part: unknown) => parseContentPart({ part, index })) };
+ }
+ throw new Error(`Message ${index + 1} needs "content" as a string or an array of content parts.`);
+ });
+}
+
+function parseContentPart({ part, index }: ParseContentPartParams): MessageChunk {
+ if (hfHub.isRecord(part) && part['type'] === 'text' && typeof part['text'] === 'string') {
+ return { type: 'text', text: part['text'] };
+ }
+ if (hfHub.isRecord(part) && part['type'] === 'image_url') {
+ const imageUrl = part['image_url'];
+ const url = hfHub.isRecord(imageUrl) ? imageUrl['url'] : imageUrl;
+ if (typeof url === 'string') {
+ return { type: 'image_url', image_url: { url } };
+ }
+ }
+ throw new Error(
+ `Message ${index + 1} has an invalid content part. Use {"type": "text", "text": "..."} or {"type": "image_url", "image_url": {"url": "..."}}.`
+ );
+}
+
+function buildResponseFormat({ format, schema }: BuildResponseFormatParams): {
+ response_format?: ResponseFormat;
+} {
+ switch (format) {
+ case undefined:
+ case 'text':
+ return {};
+ case 'json_object':
+ return { response_format: { type: 'json_object' } };
+ case 'json_schema': {
+ const raw: unknown = typeof schema === 'string' ? parseJson(schema) : schema;
+ if (!hfHub.isRecord(raw)) {
+ throw new Error('JSON Schema is required when Response Format is json_schema.');
+ }
+ const inner = raw['schema'];
+ const name = raw['name'];
+ const strict = raw['strict'];
+ if (hfHub.isRecord(inner)) {
+ return {
+ response_format: {
+ type: 'json_schema',
+ json_schema: {
+ name: typeof name === 'string' ? name : 'response',
+ schema: inner,
+ ...(typeof strict === 'boolean' ? { strict } : {}),
+ },
+ },
+ };
+ }
+ return { response_format: { type: 'json_schema', json_schema: { name: 'response', schema: raw } } };
+ }
+ default:
+ throw new Error(`Unknown Response Format '${format}'. Use text, json_object or json_schema.`);
+ }
+}
+
+function parseJson(text: string): unknown {
+ try {
+ const parsed: unknown = JSON.parse(text);
+ return parsed;
+ } catch {
+ throw new Error('Expected valid JSON.');
+ }
+}
+
+type ParseContentPartParams = {
+ part: unknown;
+ index: number;
+};
+
+type BuildResponseFormatParams = {
+ format: string | undefined;
+ schema: unknown;
+};
+
+type ResponseFormat = NonNullable<ChatCompletionInput['response_format']>;
+
+type MessageChunk = Extract<NonNullable<ChatCompletionInputMessage['content']>, unknown[]>[number];
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/generate-embeddings.ts b/packages/pieces/community/hugging-face/src/lib/actions/generate-embeddings.ts
new file mode 100644
index 00000000000..c443a39b155
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/generate-embeddings.ts
@@ -0,0 +1,147 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { InferenceClient } from '@huggingface/inference';
+import { huggingFaceAuth } from '../auth';
+import { hfInference } from '../common/inference';
+import { hfUtils } from '../common/utils';
+import { generateEmbeddingsOutputSchema } from '../output-schemas';
+
+const DEFAULT_EMBEDDING_MODEL = 'BAAI/bge-small-en-v1.5';
+
+export const generateEmbeddings = createAction({
+ auth: huggingFaceAuth,
+ name: 'generate_embeddings',
+ classification: 'READ',
+ displayName: 'Generate Text Embeddings',
+ description: 'Turn text into embedding vectors with a feature-extraction model served by Inference Providers.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Converts one or more texts into numeric embedding vectors with a Hugging Face feature-extraction model served by Inference Providers, for semantic search, clustering or similarity. One text returns a single embedding with its dimensions; several texts return one vector per text in the same order. Spends Inference Providers credits; the result is deterministic for a fixed model, so it is safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: generateEmbeddingsOutputSchema,
+ props: {
+ model: Property.ShortText({
+ displayName: 'Model',
+ description:
+ "Feature-extraction model ID, for example 'BAAI/bge-small-en-v1.5' (384 dimensions) or 'intfloat/multilingual-e5-large'. Find others with Search Models (pipeline_tag 'feature-extraction', inference_provider 'all'); append ':<provider>' to pick the provider.",
+ required: true,
+ defaultValue: DEFAULT_EMBEDDING_MODEL,
+ }),
+ provider: hfInference.providerProp(),
+ inputs: Property.Array({
+ displayName: 'Texts',
+ description: 'The texts to embed. One text returns one embedding; several texts return one embedding each, in order.',
+ required: true,
+ }),
+ normalize: hfInference.optionalBooleanProp({
+ displayName: 'Normalize',
+ description: 'Scale each vector to unit length. Leave empty for the model default.',
+ }),
+ truncate: hfInference.optionalBooleanProp({
+ displayName: 'Truncate',
+ description: "Cut texts longer than the model's maximum input length instead of failing. Leave empty for the model default.",
+ }),
+ truncation_direction: Property.StaticDropdown({
+ displayName: 'Truncation Direction',
+ description: 'Which end of an over-long text to cut when truncating. Leave empty for the model default (right).',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Right (keep the start)', value: 'right' },
+ { label: 'Left (keep the end)', value: 'left' },
+ ],
+ },
+ }),
+ prompt_name: Property.ShortText({
+ displayName: 'Prompt Name',
+ description:
+ "Name of a prompt template defined in the model's Sentence Transformers config, for example 'query' or 'passage' for retrieval models. Leave empty when the model has none.",
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { model, provider, inputs, normalize, truncate, truncation_direction, prompt_name } = context.propsValue;
+ const raw: unknown = inputs;
+ const texts = typeof raw === 'string' ? hfUtils.toStringArray([raw]) : hfUtils.toStringArray(raw);
+ if (texts.length === 0) {
+ throw new Error('Provide at least one non-empty text to embed.');
+ }
+ const resolved = hfInference.resolveModelAndProvider({ model, provider, defaultModel: DEFAULT_EMBEDDING_MODEL });
+ const normalizeFlag = hfUtils.booleanFlag(normalize);
+ const truncateFlag = hfUtils.booleanFlag(truncate);
+ const direction = truncation_direction === 'left' || truncation_direction === 'right' ? truncation_direction : undefined;
+ const promptName = prompt_name?.trim();
+ const client = new InferenceClient(context.auth.secret_text);
+ try {
+ const output = await client.featureExtraction({
+ model: resolved.model,
+ provider: resolved.provider,
+ inputs: texts.length === 1 ? texts[0] : texts,
+ ...(normalizeFlag !== undefined ? { normalize: normalizeFlag } : {}),
+ ...(truncateFlag !== undefined ? { truncate: truncateFlag } : {}),
+ ...(direction ? { truncation_direction: direction } : {}),
+ ...(promptName ? { prompt_name: promptName } : {}),
+ });
+ const embeddings = toPooledEmbeddings({ output, count: texts.length });
+ if (texts.length === 1) {
+ const embedding = embeddings[0];
+ return { model: resolved.model, embedding, dimensions: embedding.length };
+ }
+ return {
+ model: resolved.model,
+ embeddings,
+ count: embeddings.length,
+ dimensions: embeddings[0]?.length ?? 0,
+ };
+ } catch (error) {
+ throw hfInference.toError(error);
+ }
+ },
+});
+
+function toPooledEmbeddings({ output, count }: ToPooledEmbeddingsParams): number[][] {
+ if (isNumberArray(output)) {
+ if (count === 1) {
+ return [output];
+ }
+ throw new Error(NOT_ONE_PER_TEXT_MESSAGE);
+ }
+ if (!Array.isArray(output)) {
+ throw new Error(NOT_ONE_PER_TEXT_MESSAGE);
+ }
+ const items: unknown[] = output;
+ if (items.some(isNumberMatrix)) {
+ throw new Error(TOKEN_LEVEL_MESSAGE);
+ }
+ const rows = items.filter(isNumberArray);
+ if (rows.length !== items.length) {
+ throw new Error(NOT_ONE_PER_TEXT_MESSAGE);
+ }
+ if (count === 1 && rows.length > 1) {
+ throw new Error(TOKEN_LEVEL_MESSAGE);
+ }
+ if (rows.length !== count) {
+ throw new Error(NOT_ONE_PER_TEXT_MESSAGE);
+ }
+ return rows;
+}
+
+function isNumberMatrix(value: unknown): value is number[][] {
+ return Array.isArray(value) && value.length > 0 && value.every(isNumberArray);
+}
+
+function isNumberArray(value: unknown): value is number[] {
+ return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === 'number');
+}
+
+const TOKEN_LEVEL_MESSAGE =
+ 'The model returned token-level vectors instead of one pooled embedding per text. Use a sentence-embedding model such as BAAI/bge-small-en-v1.5.';
+const NOT_ONE_PER_TEXT_MESSAGE =
+ 'The model did not return one pooled embedding per text. Use a sentence-embedding model such as BAAI/bge-small-en-v1.5.';
+
+type ToPooledEmbeddingsParams = {
+ output: unknown;
+ count: number;
+};
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-collection.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-collection.ts
new file mode 100644
index 00000000000..8841ba6ddad
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-collection.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { getCollectionOutputSchema } from '../output-schemas';
+
+export const getCollection = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_collection',
+ classification: 'READ',
+ displayName: 'Get Collection',
+ description: 'Get one Hugging Face collection with all of its items.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns one Hugging Face collection by its slug: title, description, owner, visibility, upvotes and every item (models, datasets, Spaces, papers or nested collections) with its type, ID and note. Get the slug from List Collections or the collection URL. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: getCollectionOutputSchema,
+ props: {
+ slug: Property.ShortText({
+ displayName: 'Collection Slug',
+ description:
+ "The full collection slug in 'namespace/title-id' form, for example 'meta-llama/llama-32-66f448ffc8c32f949b04c8cf' (the part after huggingface.co/collections/).",
+ required: true,
+ }),
+ },
+ async run(context) {
+ const segments = context.propsValue.slug
+ .trim()
+ .replace(/^https?:\/\/huggingface\.co\/collections\//, '')
+ .split('/')
+ .filter((segment) => segment.length > 0);
+ if (segments.length !== 2) {
+ throw new Error(
+ "Invalid collection slug. Use the 'namespace/title-id' form, for example 'meta-llama/llama-32-66f448ffc8c32f949b04c8cf'."
+ );
+ }
+ const path = `/api/collections/${segments.map(encodeURIComponent).join('/')}`;
+ const token = context.auth.secret_text;
+ try {
+ const response = await hfHub.request<unknown>({ token, method: HttpMethod.GET, path });
+ return response.body;
+ } catch (error) {
+ try {
+ const response = await hfHub.request<unknown>({ token, method: HttpMethod.GET, path, anonymous: true });
+ return response.body;
+ } catch {
+ throw error;
+ }
+ }
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-current-user.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-current-user.ts
new file mode 100644
index 00000000000..c78c9bbee4d
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-current-user.ts
@@ -0,0 +1,86 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { getCurrentUserOutputSchema } from '../output-schemas';
+
+export const getCurrentUser = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_current_user',
+ classification: 'READ',
+ displayName: 'Get Current User & Token',
+ description: 'Get the Hugging Face account behind the connection and the role of its access token.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns the account behind the connected token (username, full name, email, PRO status, organizations with the user's role in each) and the token's name, role ('read', 'write' or 'fineGrained') and fine-grained permissions. Call it first to learn the username or organization namespaces, or to diagnose 401/403 errors: a 'read' token cannot perform Hub writes. Never returns the token value. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: getCurrentUserOutputSchema,
+ props: {},
+ async run(context) {
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/api/whoami-v2',
+ });
+ const body = hfHub.isRecord(response.body) ? response.body : {};
+ const accessToken = pickRecord({ source: pickRecord({ source: body, key: 'auth' }), key: 'accessToken' });
+ const fineGrained = pickRecord({ source: accessToken, key: 'fineGrained' });
+ const orgs = Array.isArray(body['orgs']) ? body['orgs'].filter(hfHub.isRecord) : [];
+ const scoped = Array.isArray(fineGrained?.['scoped']) ? fineGrained['scoped'].filter(hfHub.isRecord) : [];
+ return {
+ username: pickString({ source: body, key: 'name' }),
+ full_name: pickString({ source: body, key: 'fullname' }),
+ email: pickString({ source: body, key: 'email' }),
+ email_verified: pickBoolean({ source: body, key: 'emailVerified' }),
+ is_pro: pickBoolean({ source: body, key: 'isPro' }),
+ avatar_url: pickString({ source: body, key: 'avatarUrl' }),
+ account_type: pickString({ source: body, key: 'type' }),
+ organizations: orgs.map((org) => ({
+ name: pickString({ source: org, key: 'name' }),
+ full_name: pickString({ source: org, key: 'fullname' }),
+ role_in_org: pickString({ source: org, key: 'roleInOrg' }),
+ is_enterprise: pickBoolean({ source: org, key: 'isEnterprise' }),
+ })),
+ token_name: pickString({ source: accessToken, key: 'displayName' }),
+ token_role: pickString({ source: accessToken, key: 'role' }),
+ token_created_at: pickString({ source: accessToken, key: 'createdAt' }),
+ token_can_read_gated_repos: pickBoolean({ source: fineGrained, key: 'canReadGatedRepos' }),
+ token_global_permissions: pickStringArray({ source: fineGrained, key: 'global' }),
+ token_scoped_permissions: scoped.map((scope) => {
+ const entity = pickRecord({ source: scope, key: 'entity' });
+ return {
+ entity_type: pickString({ source: entity, key: 'type' }),
+ entity_name: pickString({ source: entity, key: 'name' }),
+ permissions: pickStringArray({ source: scope, key: 'permissions' }),
+ };
+ }),
+ };
+ },
+});
+
+function pickRecord({ source, key }: PickParams): Record<string, unknown> | null {
+ const value = source?.[key];
+ return hfHub.isRecord(value) ? value : null;
+}
+
+function pickString({ source, key }: PickParams): string | null {
+ const value = source?.[key];
+ return typeof value === 'string' ? value : null;
+}
+
+function pickBoolean({ source, key }: PickParams): boolean | null {
+ const value = source?.[key];
+ return typeof value === 'boolean' ? value : null;
+}
+
+function pickStringArray({ source, key }: PickParams): string[] {
+ const value = source?.[key];
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
+}
+
+type PickParams = {
+ source: Record<string, unknown> | null;
+ key: string;
+};
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-dataset.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset.ts
new file mode 100644
index 00000000000..7d38bf5c9b6
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-dataset.ts
@@ -0,0 +1,36 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { getDatasetOutputSchema } from '../output-schemas';
+
+export const getDataset = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_dataset',
+ classification: 'READ',
+ displayName: 'Get Dataset',
+ description: 'Get the Hub metadata of one dataset repository.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns the Hub repository metadata of one dataset: card data, tags, file list (siblings), gating, downloads and likes, optionally at a specific revision. Use it after Search Datasets to inspect a dataset repository; its README or other text files can then be read with Read Repo File. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: getDatasetOutputSchema,
+ props: {
+ repo_id: hfProps.repoId(),
+ revision: hfProps.optionalRevision(),
+ },
+ async run(context) {
+ const { repo_id, revision } = context.propsValue;
+ const revisionPath = revision?.trim() ? `/revision/${hfRepo.encodeRevision(revision)}` : '';
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/api/datasets/${hfRepo.encodeRepoId(repo_id)}${revisionPath}`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-discussion.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-discussion.ts
new file mode 100644
index 00000000000..3a16537fe73
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-discussion.ts
@@ -0,0 +1,45 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { getDiscussionOutputSchema } from '../output-schemas';
+
+export const getDiscussion = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_discussion',
+ classification: 'READ',
+ displayName: 'Get Discussion or PR',
+ description: 'Get one discussion or pull request of a Hub repository, with its comments and events.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns one discussion or pull request of a Hub repository by its per-repository number: title, status, author, every comment and status/title event and, for pull requests, the diff URL, target branch and merge info. Get the number from List Discussions & PRs. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: getDiscussionOutputSchema,
+ props: {
+ repo_type: hfProps.repoType(),
+ repo_id: hfProps.repoId(),
+ discussion_number: Property.Number({
+ displayName: 'Discussion Number',
+ description: "The discussion or pull request number within the repository, for example 12 (the 'num' from List Discussions & PRs).",
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { repo_type, repo_id, discussion_number } = context.propsValue;
+ if (!Number.isInteger(discussion_number) || discussion_number < 1) {
+ throw new Error('Discussion Number must be a positive whole number.');
+ }
+ const token = context.auth.secret_text;
+ const apiPath = await hfRepo.apiPath({ token, repoType: repo_type, repoId: repo_id });
+ const response = await hfHub.request<unknown>({
+ token,
+ method: HttpMethod.GET,
+ path: `${apiPath}/discussions/${discussion_number}`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-model.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-model.ts
new file mode 100644
index 00000000000..2b07d2fdd28
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-model.ts
@@ -0,0 +1,36 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { getModelOutputSchema } from '../output-schemas';
+
+export const getModel = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_model',
+ classification: 'READ',
+ displayName: 'Get Model',
+ description: 'Get the Hub metadata of one model repository.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns the Hub metadata of one model: card data, tags, pipeline_tag, library, file list (siblings), gating, downloads and likes, optionally at a specific revision. Use it after Search Models to inspect a model before running it or reading its files with Read Repo File. Legacy un-namespaced IDs such as 'gpt2' are followed to their canonical owner. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: getModelOutputSchema,
+ props: {
+ repo_id: hfProps.repoId(),
+ revision: hfProps.optionalRevision(),
+ },
+ async run(context) {
+ const { repo_id, revision } = context.propsValue;
+ const revisionPath = revision?.trim() ? `/revision/${hfRepo.encodeRevision(revision)}` : '';
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/api/models/${hfRepo.encodeRepoId(repo_id)}${revisionPath}`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-organization-overview.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-organization-overview.ts
new file mode 100644
index 00000000000..422e1751edd
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-organization-overview.ts
@@ -0,0 +1,35 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { getOrganizationOverviewOutputSchema } from '../output-schemas';
+
+export const getOrganizationOverview = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_organization_overview',
+ classification: 'READ',
+ displayName: 'Get Organization Profile',
+ description: 'Get the public profile of a Hugging Face organization.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns the public profile of a Hugging Face organization: full name, avatar URL, verification and Enterprise status, follower and member counts, and how many models, datasets and Spaces it owns. Use List Organization Members for its members and Get User Profile for an individual user. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: getOrganizationOverviewOutputSchema,
+ props: {
+ organization: Property.ShortText({
+ displayName: 'Organization',
+ description: "The organization's Hub name, for example 'huggingface' or 'meta-llama'.",
+ required: true,
+ }),
+ },
+ async run(context) {
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/api/organizations/${encodeURIComponent(context.propsValue.organization.trim())}/overview`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-paper.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-paper.ts
new file mode 100644
index 00000000000..0fcc41a6f1c
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-paper.ts
@@ -0,0 +1,58 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfUtils } from '../common/utils';
+import { getPaperOutputSchema } from '../output-schemas';
+
+export const getPaper = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_paper',
+ classification: 'READ',
+ displayName: 'Get Paper',
+ description: 'Get the details of one research paper on Hugging Face.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns one research paper on Hugging Face Papers by its arXiv ID: title, authors, summary, publish date, upvotes and linked resources, plus its discussion comments (with comment IDs) when Include Comments is on. Get the ID from Search Papers or List Daily Papers. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: getPaperOutputSchema,
+ props: {
+ paper_id: Property.ShortText({
+ displayName: 'Paper ID',
+ description: "The paper's arXiv ID, for example '2307.09288'.",
+ required: true,
+ }),
+ include_comments: Property.Checkbox({
+ displayName: 'Include Comments',
+ description: 'Also return the comments on the paper page, with their comment IDs.',
+ required: false,
+ defaultValue: false,
+ }),
+ include_submission_deadline: Property.Checkbox({
+ displayName: 'Include Submission Deadline',
+ description: 'Also return the conference submission deadline linked to the paper, when there is one.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run(context) {
+ const { paper_id, include_comments, include_submission_deadline } = context.propsValue;
+ const paperId = paper_id.trim();
+ if (paperId.length === 0) {
+ throw new Error('Paper ID is required.');
+ }
+ const fields = hfUtils.toStringArray([
+ include_comments ? 'comments' : '',
+ include_submission_deadline ? 'submissionDeadline' : '',
+ ]);
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/api/papers/${encodeURIComponent(paperId)}`,
+ query: fields.map((field): [string, string] => ['field', field]),
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-repo-paths-info.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-repo-paths-info.ts
new file mode 100644
index 00000000000..4e2829a1aa8
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-repo-paths-info.ts
@@ -0,0 +1,56 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { hfUtils } from '../common/utils';
+import { getRepoPathsInfoOutputSchema } from '../output-schemas';
+
+export const getRepoPathsInfo = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_repo_paths_info',
+ classification: 'READ',
+ displayName: 'Get File/Folder Info',
+ description: 'Get size, LFS and last-commit details for specific files or folders in a repository.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns details for up to 2000 known paths in a Hub repository at a revision: type (file or directory), size, blob id, LFS info and, with Include Last Commit, the last commit and security status. Use it when you already know the paths (from List Repo Files) and need their sizes, for example to check a file fits the Read Repo File limit. Read-only and safe to retry; paths that do not exist are simply left out.',
+ idempotent: true,
+ },
+ outputSchema: getRepoPathsInfoOutputSchema,
+ props: {
+ repo_type: hfProps.repoType(),
+ repo_id: hfProps.repoId(),
+ revision: hfProps.revision(),
+ paths: Property.Array({
+ displayName: 'Paths',
+ description: "File or folder paths inside the repository, for example 'config.json' or 'onnx/model.onnx'. Up to 2000.",
+ required: true,
+ }),
+ expand: Property.Checkbox({
+ displayName: 'Include Last Commit',
+ description: 'Add the last commit and security-scan status for each path.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run(context) {
+ const { repo_type, repo_id, revision, paths, expand } = context.propsValue;
+ const pathList = hfUtils.toStringArray(paths);
+ if (pathList.length === 0 || pathList.length > 2000) {
+ throw new Error('Provide between 1 and 2000 paths.');
+ }
+ const token = context.auth.secret_text;
+ const apiPath = await hfRepo.apiPath({ token, repoType: repo_type, repoId: repo_id });
+ const response = await hfHub.request<unknown>({
+ token,
+ method: HttpMethod.POST,
+ path: `${apiPath}/paths-info/${hfRepo.encodeRevision(revision)}`,
+ body: { paths: pathList, expand: expand === true },
+ });
+ const entries = Array.isArray(response.body) ? response.body : [];
+ return { paths: entries, count: entries.length };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-repo-security-scan.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-repo-security-scan.ts
new file mode 100644
index 00000000000..77a161e9adf
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-repo-security-scan.ts
@@ -0,0 +1,37 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { getRepoSecurityScanOutputSchema } from '../output-schemas';
+
+export const getRepoSecurityScan = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_repo_security_scan',
+ classification: 'READ',
+ displayName: 'Get Security Scan',
+ description: 'Get the malware and pickle security-scan status of a repository.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns the Hub's malware and pickle-import security scan status for a repository: whether scans are done and which files were flagged, each with a level such as safe, caution, suspicious or unsafe. Use it as a safety check before recommending that someone download or load a model's weights. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: getRepoSecurityScanOutputSchema,
+ props: {
+ repo_type: hfProps.repoType(),
+ repo_id: hfProps.repoId(),
+ },
+ async run(context) {
+ const { repo_type, repo_id } = context.propsValue;
+ const token = context.auth.secret_text;
+ const apiPath = await hfRepo.apiPath({ token, repoType: repo_type, repoId: repo_id });
+ const response = await hfHub.request<unknown>({
+ token,
+ method: HttpMethod.GET,
+ path: `${apiPath}/scan`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-repo-size.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-repo-size.ts
new file mode 100644
index 00000000000..3fbbca204e9
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-repo-size.ts
@@ -0,0 +1,44 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { getRepoSizeOutputSchema } from '../output-schemas';
+
+export const getRepoSize = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_repo_size',
+ classification: 'READ',
+ displayName: 'Get Repo Size',
+ description: 'Get the total size in bytes of a repository, or of one folder in it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the total size in bytes of every file under a path of a Hub repository at a revision (the whole repository when the path is empty), counting LFS files at their real size. Use it to judge download cost before fetching a model; for per-file sizes use List Repo Files or Get File/Folder Info. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: getRepoSizeOutputSchema,
+ props: {
+ repo_type: hfProps.repoType(),
+ repo_id: hfProps.repoId(),
+ revision: hfProps.revision(),
+ path: Property.ShortText({
+ displayName: 'Folder Path',
+ description: "Folder to measure, for example 'onnx'. Leave empty for the whole repository.",
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { repo_type, repo_id, revision, path } = context.propsValue;
+ const token = context.auth.secret_text;
+ const apiPath = await hfRepo.apiPath({ token, repoType: repo_type, repoId: repo_id });
+ const encodedPath = hfRepo.encodeFilePath(path);
+ const response = await hfHub.request<unknown>({
+ token,
+ method: HttpMethod.GET,
+ path: `${apiPath}/treesize/${hfRepo.encodeRevision(revision)}${encodedPath ? `/${encodedPath}` : ''}`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-space.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-space.ts
new file mode 100644
index 00000000000..566e59988fe
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-space.ts
@@ -0,0 +1,36 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { getSpaceOutputSchema } from '../output-schemas';
+
+export const getSpace = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_space',
+ classification: 'READ',
+ displayName: 'Get Space',
+ description: 'Get the Hub metadata of one Space.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns the Hub metadata of one Space: its SDK, runtime stage (for example RUNNING, BUILDING, SLEEPING or RUNTIME_ERROR), hardware, file list, tags and likes, optionally at a specific revision. Use it after Search Spaces to check whether a Space is up and how it is built. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: getSpaceOutputSchema,
+ props: {
+ repo_id: hfProps.repoId(),
+ revision: hfProps.optionalRevision(),
+ },
+ async run(context) {
+ const { repo_id, revision } = context.propsValue;
+ const revisionPath = revision?.trim() ? `/revision/${hfRepo.encodeRevision(revision)}` : '';
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/api/spaces/${hfRepo.encodeRepoId(repo_id)}${revisionPath}`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/get-user-overview.ts b/packages/pieces/community/hugging-face/src/lib/actions/get-user-overview.ts
new file mode 100644
index 00000000000..e3128ebb415
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/get-user-overview.ts
@@ -0,0 +1,35 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { getUserOverviewOutputSchema } from '../output-schemas';
+
+export const getUserOverview = createAction({
+ auth: huggingFaceAuth,
+ name: 'get_user_overview',
+ classification: 'READ',
+ displayName: 'Get User Profile',
+ description: 'Get the public profile of a Hugging Face user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns the public profile of a Hugging Face user: full name, avatar URL, PRO status, organizations, follower counts and how many models, datasets and Spaces they own. Use Get Current User & Token for the connected account itself and Get Organization Profile for an organization. Social handles are not included. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: getUserOverviewOutputSchema,
+ props: {
+ username: Property.ShortText({
+ displayName: 'Username',
+ description: "The user's Hub username, for example 'julien-c'.",
+ required: true,
+ }),
+ },
+ async run(context) {
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/api/users/${encodeURIComponent(context.propsValue.username.trim())}/overview`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/language-translation.ts b/packages/pieces/community/hugging-face/src/lib/actions/language-translation.ts
index a2a0ddf4bcc..f2a889d1455 100644
--- a/packages/pieces/community/hugging-face/src/lib/actions/language-translation.ts
+++ b/packages/pieces/community/hugging-face/src/lib/actions/language-translation.ts
@@ -14,7 +14,7 @@ export const languageTranslation = createAction({
'Translate text between languages using specialized Hugging Face translation models',
aiMetadata: {
description:
- 'Translates a block of text with a dedicated Hugging Face machine-translation model, chosen either from the dropdown of Helsinki-NLP opus-mt language pairs or by passing any translation model ID in the custom-model field, which takes precedence over the dropdown. Use it instead of chat_completion whenever the task is purely translation, since these models are narrower and more consistent; the source and target language codes apply only to multilingual models, because a single-pair model already fixes the direction. Read-only and idempotent: it returns the translation and stores nothing.',
+ 'Translates a block of text with a dedicated Hugging Face machine-translation model, chosen either from the dropdown of Helsinki-NLP opus-mt language pairs or by passing any translation model ID in the custom-model field, which takes precedence over the dropdown. Use it instead of generate_chat_completion whenever the task is purely translation, since these models are narrower and more consistent; the source and target language codes apply only to multilingual models, because a single-pair model already fixes the direction. Read-only and idempotent: it returns the translation and stores nothing.',
idempotent: true,
},
outputSchema: languageTranslationOutputSchema,
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-collections.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-collections.ts
new file mode 100644
index 00000000000..94b9baa37fe
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-collections.ts
@@ -0,0 +1,78 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfUtils } from '../common/utils';
+import { listCollectionsOutputSchema } from '../output-schemas';
+
+export const listCollections = createAction({
+ auth: huggingFaceAuth,
+ name: 'list_collections',
+ classification: 'SEARCH',
+ displayName: 'List Collections',
+ description: 'List or search curated collections on the Hugging Face Hub.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Lists Hugging Face collections (curated groups of models, datasets, Spaces and papers), filterable by owner, contained item and text, one page per call with a next_cursor. Each entry carries its slug ('namespace/title-id'), which Get Collection needs to return every item. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: listCollectionsOutputSchema,
+ props: {
+ owner: Property.ShortText({
+ displayName: 'Owner',
+ description: "Only collections owned by this user or organization, for example 'huggingface'.",
+ required: false,
+ }),
+ item: Property.ShortText({
+ displayName: 'Contains Item',
+ description:
+ "Only collections that contain this item, written as '<type>/<id>', for example 'models/openai-community/gpt2', 'datasets/stanfordnlp/imdb' or 'papers/2307.09288'.",
+ required: false,
+ }),
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: 'Only collections whose title matches this text.',
+ required: false,
+ }),
+ sort: Property.StaticDropdown({
+ displayName: 'Sort By',
+ description: 'Sort order. Defaults to trending.',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Trending', value: 'trending' },
+ { label: 'Upvotes', value: 'upvotes' },
+ { label: 'Recently Updated', value: 'lastModified' },
+ ],
+ },
+ }),
+ limit: hfProps.limit({ defaultValue: 10, max: 100 }),
+ cursor: hfProps.cursor(),
+ },
+ async run(context) {
+ const { owner, item, search, sort, limit, cursor } = context.propsValue;
+ hfUtils.assertLimit({ value: limit, min: 1, max: 100, name: 'Limit' });
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/api/collections',
+ query: [
+ ['owner', owner],
+ ['item', item],
+ ['q', search],
+ ['sort', sort],
+ ['limit', limit],
+ ['cursor', cursor],
+ ],
+ });
+ const collections = Array.isArray(response.body) ? response.body : [];
+ return {
+ collections,
+ count: collections.length,
+ next_cursor: hfHub.parseNextCursor(response.headers),
+ };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-daily-papers.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-daily-papers.ts
new file mode 100644
index 00000000000..d21a965e510
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-daily-papers.ts
@@ -0,0 +1,91 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfUtils } from '../common/utils';
+import { listDailyPapersOutputSchema } from '../output-schemas';
+
+export const listDailyPapers = createAction({
+ auth: huggingFaceAuth,
+ name: 'list_daily_papers',
+ classification: 'SEARCH',
+ displayName: 'List Daily Papers',
+ description: "List the research papers featured on Hugging Face's Daily Papers page.",
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Lists the research papers featured on Hugging Face Daily Papers for one day, ISO week or month (or the latest when none is given), sorted by publish date or trending, one page per call with next_page. Set at most one of Date, Week or Month. Use Search Papers to find papers by topic and Get Paper for one paper's details. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: listDailyPapersOutputSchema,
+ props: {
+ date: Property.ShortText({
+ displayName: 'Date',
+ description: "Papers featured on this day, in 'YYYY-MM-DD' form, for example '2026-09-22'.",
+ required: false,
+ }),
+ week: Property.ShortText({
+ displayName: 'Week',
+ description: "Papers featured in this ISO week, in 'YYYY-Www' form, for example '2026-W38'.",
+ required: false,
+ }),
+ month: Property.ShortText({
+ displayName: 'Month',
+ description: "Papers featured in this month, in 'YYYY-MM' form, for example '2026-09'.",
+ required: false,
+ }),
+ submitter: Property.ShortText({
+ displayName: 'Submitter',
+ description: 'Only papers submitted by this Hub username.',
+ required: false,
+ }),
+ sort: Property.StaticDropdown({
+ displayName: 'Sort By',
+ description: 'Sort order. Defaults to publish date.',
+ required: false,
+ defaultValue: 'publishedAt',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Publish Date', value: 'publishedAt' },
+ { label: 'Trending', value: 'trending' },
+ ],
+ },
+ }),
+ limit: hfProps.limit({ defaultValue: 50, max: 100 }),
+ page: hfProps.page(),
+ },
+ async run(context) {
+ const { date, week, month, submitter, sort, limit, page } = context.propsValue;
+ hfUtils.assertLimit({ value: limit, min: 1, max: 100, name: 'Limit' });
+ hfUtils.assertLimit({ value: page, min: 0, max: Number.MAX_SAFE_INTEGER, name: 'Page' });
+ const periods = [date, week, month].filter((value) => value !== undefined && value.trim().length > 0);
+ if (periods.length > 1) {
+ throw new Error('Set at most one of Date, Week or Month.');
+ }
+ const pageNumber = page ?? 0;
+ const pageSize = limit ?? 50;
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/api/daily_papers',
+ query: [
+ ['date', date?.trim()],
+ ['week', week?.trim()],
+ ['month', month?.trim()],
+ ['submitter', submitter],
+ ['sort', sort],
+ ['limit', pageSize],
+ ['p', pageNumber],
+ ],
+ });
+ const papers = Array.isArray(response.body) ? response.body : [];
+ return {
+ papers,
+ count: papers.length,
+ page: pageNumber,
+ next_page: papers.length >= pageSize ? pageNumber + 1 : null,
+ };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-discussions.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-discussions.ts
new file mode 100644
index 00000000000..aefd76b718b
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-discussions.ts
@@ -0,0 +1,112 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { hfUtils } from '../common/utils';
+import { listDiscussionsOutputSchema } from '../output-schemas';
+
+export const listDiscussions = createAction({
+ auth: huggingFaceAuth,
+ name: 'list_discussions',
+ classification: 'SEARCH',
+ displayName: 'List Discussions & PRs',
+ description: 'List the discussions and pull requests of a Hub repository.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Lists the discussions and pull requests of a model, dataset or Space repository, one page per call (page-number pagination with next_page), filterable by kind, status, author and text search. Each entry carries its per-repository number, which Get Discussion or PR needs. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: listDiscussionsOutputSchema,
+ props: {
+ repo_type: hfProps.repoType(),
+ repo_id: hfProps.repoId(),
+ kind: Property.StaticDropdown({
+ displayName: 'Kind',
+ description: 'Only discussions, only pull requests, or both. Defaults to both.',
+ required: false,
+ defaultValue: 'all',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'All', value: 'all' },
+ { label: 'Discussions', value: 'discussion' },
+ { label: 'Pull Requests', value: 'pull_request' },
+ ],
+ },
+ }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ description: 'Only open, only closed, or both. Defaults to both.',
+ required: false,
+ defaultValue: 'all',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'All', value: 'all' },
+ { label: 'Open', value: 'open' },
+ { label: 'Closed', value: 'closed' },
+ ],
+ },
+ }),
+ author: Property.ShortText({
+ displayName: 'Author',
+ description: "Only threads opened by this Hub username, for example 'julien-c'.",
+ required: false,
+ }),
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: 'Only threads whose title matches this text.',
+ required: false,
+ }),
+ sort: Property.StaticDropdown({
+ displayName: 'Sort By',
+ description: 'Sort order. Defaults to most recently created.',
+ required: false,
+ defaultValue: 'recently-created',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Recently Created', value: 'recently-created' },
+ { label: 'Trending', value: 'trending' },
+ { label: 'Most Reactions', value: 'reactions' },
+ ],
+ },
+ }),
+ page: hfProps.page(),
+ },
+ async run(context) {
+ const { repo_type, repo_id, kind, status, author, search, sort, page } = context.propsValue;
+ hfUtils.assertLimit({ value: page, min: 0, max: Number.MAX_SAFE_INTEGER, name: 'Page' });
+ const token = context.auth.secret_text;
+ const pageNumber = page ?? 0;
+ const apiPath = await hfRepo.apiPath({ token, repoType: repo_type, repoId: repo_id });
+ const response = await hfHub.request<unknown>({
+ token,
+ method: HttpMethod.GET,
+ path: `${apiPath}/discussions`,
+ query: [
+ ['p', pageNumber],
+ ['type', kind],
+ ['status', status],
+ ['author', author],
+ ['search', search],
+ ['sort', sort],
+ ],
+ });
+ const body = hfHub.isRecord(response.body) ? response.body : {};
+ const discussions = Array.isArray(body['discussions']) ? body['discussions'] : [];
+ const totalCount = typeof body['count'] === 'number' ? body['count'] : null;
+ const start = typeof body['start'] === 'number' ? body['start'] : 0;
+ const hasMore = totalCount !== null && start + discussions.length < totalCount;
+ return {
+ discussions,
+ count: discussions.length,
+ total_count: totalCount,
+ page: pageNumber,
+ next_page: hasMore ? pageNumber + 1 : null,
+ };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-hub-tags.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-hub-tags.ts
new file mode 100644
index 00000000000..66abd9c1e61
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-hub-tags.ts
@@ -0,0 +1,88 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { listHubTagsOutputSchema } from '../output-schemas';
+
+const MODEL_TAG_TYPES = [
+ 'pipeline_tag',
+ 'library',
+ 'dataset',
+ 'language',
+ 'license',
+ 'arxiv',
+ 'doi',
+ 'region',
+ 'deploy',
+ 'other',
+];
+
+const DATASET_TAG_TYPES = [
+ 'benchmark',
+ 'task_categories',
+ 'task_ids',
+ 'size_categories',
+ 'modality',
+ 'format',
+ 'library',
+ 'language',
+ 'license',
+ 'arxiv',
+ 'doi',
+ 'region',
+ 'annotations_creators',
+ 'language_creators',
+ 'multilinguality',
+ 'source_datasets',
+ 'other',
+];
+
+export const listHubTags = createAction({
+ auth: huggingFaceAuth,
+ name: 'list_hub_tags',
+ classification: 'SEARCH',
+ displayName: 'List Hub Tags by Type',
+ description: 'List the tags available for filtering models or datasets, grouped by tag type.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Lists the Hub's valid filter tags for models or datasets, grouped by tag type (for models: pipeline_tag, library, language, license and more; for datasets: task_categories, size_categories, modality, format and more). Call it to find the exact 'filter' values to pass to Search Models or Search Datasets. Spaces have no tag catalogue. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: listHubTagsOutputSchema,
+ props: {
+ repo_type: Property.StaticDropdown({
+ displayName: 'Repository Type',
+ description: "Whose tags to list: 'model' or 'dataset'.",
+ required: true,
+ defaultValue: 'model',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Model', value: 'model' },
+ { label: 'Dataset', value: 'dataset' },
+ ],
+ },
+ }),
+ tag_type: Property.ShortText({
+ displayName: 'Tag Type',
+ description: `Only tags of this type. Models: ${MODEL_TAG_TYPES.join(', ')}. Datasets: ${DATASET_TAG_TYPES.join(', ')}. Leave empty for every type (large).`,
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { repo_type, tag_type } = context.propsValue;
+ const allowed = repo_type === 'dataset' ? DATASET_TAG_TYPES : MODEL_TAG_TYPES;
+ const tagType = tag_type?.trim();
+ if (tagType && !allowed.includes(tagType)) {
+ throw new Error(`Unknown tag type '${tagType}' for ${repo_type}s. Use one of: ${allowed.join(', ')}.`);
+ }
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: repo_type === 'dataset' ? '/api/datasets-tags-by-type' : '/api/models-tags-by-type',
+ query: [['type', tagType]],
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-organization-members.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-organization-members.ts
new file mode 100644
index 00000000000..7b8765be507
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-organization-members.ts
@@ -0,0 +1,62 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfUtils } from '../common/utils';
+import { listOrganizationMembersOutputSchema } from '../output-schemas';
+
+export const listOrganizationMembers = createAction({
+ auth: huggingFaceAuth,
+ name: 'list_organization_members',
+ classification: 'SEARCH',
+ displayName: 'List Organization Members',
+ description: 'List the members of a Hugging Face organization.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Lists the members of a Hugging Face organization, one page per call with a next_cursor; each member has a username, full name, avatar and, where visible, their org role. Optionally narrow by a name search. The Email filter and member emails are only available to organization admins; other tokens should leave Email empty. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: listOrganizationMembersOutputSchema,
+ props: {
+ organization: Property.ShortText({
+ displayName: 'Organization',
+ description: "The organization's Hub name, for example 'huggingface'.",
+ required: true,
+ }),
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: 'Only members whose username or full name matches this text.',
+ required: false,
+ }),
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'Only the member with this email address. Organization admins only.',
+ required: false,
+ }),
+ limit: hfProps.limit({ defaultValue: 100, max: 10000 }),
+ cursor: hfProps.cursor(),
+ },
+ async run(context) {
+ const { organization, search, email, limit, cursor } = context.propsValue;
+ hfUtils.assertLimit({ value: limit, min: 10, max: 10000, name: 'Limit' });
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/api/organizations/${encodeURIComponent(organization.trim())}/members`,
+ query: [
+ ['search', search],
+ ['email', email],
+ ['limit', limit],
+ ['cursor', cursor],
+ ],
+ });
+ const members = Array.isArray(response.body) ? response.body : [];
+ return {
+ members,
+ count: members.length,
+ next_cursor: hfHub.parseNextCursor(response.headers),
+ };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-repo-commits.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-repo-commits.ts
new file mode 100644
index 00000000000..6bc877a3077
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-repo-commits.ts
@@ -0,0 +1,57 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { hfUtils } from '../common/utils';
+import { listRepoCommitsOutputSchema } from '../output-schemas';
+
+export const listRepoCommits = createAction({
+ auth: huggingFaceAuth,
+ name: 'list_repo_commits',
+ classification: 'SEARCH',
+ displayName: 'List Repo Commits',
+ description: 'List the commit history of a branch or revision in a Hub repository.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the commit history of a Hub repository revision, newest first, one page per call (page-number pagination with next_page); each commit carries its id, title, message, authors and date. Use commit ids as revisions for Compare Revisions or Read Repo File; use List Branches & Tags to find branch names. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listRepoCommitsOutputSchema,
+ props: {
+ repo_type: hfProps.repoType(),
+ repo_id: hfProps.repoId(),
+ revision: hfProps.revision(),
+ page: hfProps.page(),
+ limit: hfProps.limit({ defaultValue: 50, max: 1000 }),
+ },
+ async run(context) {
+ const { repo_type, repo_id, revision, page, limit } = context.propsValue;
+ hfUtils.assertLimit({ value: limit, min: 1, max: 1000, name: 'Limit' });
+ hfUtils.assertLimit({ value: page, min: 0, max: Number.MAX_SAFE_INTEGER, name: 'Page' });
+ const token = context.auth.secret_text;
+ const pageNumber = page ?? 0;
+ const pageSize = limit ?? 50;
+ const apiPath = await hfRepo.apiPath({ token, repoType: repo_type, repoId: repo_id });
+ const response = await hfHub.request<unknown>({
+ token,
+ method: HttpMethod.GET,
+ path: `${apiPath}/commits/${hfRepo.encodeRevision(revision)}`,
+ query: [
+ ['p', pageNumber],
+ ['limit', pageSize],
+ ],
+ });
+ const commits = Array.isArray(response.body) ? response.body : [];
+ const linkedPage = hfHub.parseNextLinkParam({ headers: response.headers, param: 'p' });
+ const nextPage = linkedPage !== null ? Number(linkedPage) : commits.length >= pageSize ? pageNumber + 1 : null;
+ return {
+ commits,
+ count: commits.length,
+ page: pageNumber,
+ next_page: nextPage,
+ };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-repo-files.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-repo-files.ts
new file mode 100644
index 00000000000..8b8dd48cf47
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-repo-files.ts
@@ -0,0 +1,75 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { hfUtils } from '../common/utils';
+import { listRepoFilesOutputSchema } from '../output-schemas';
+
+export const listRepoFiles = createAction({
+ auth: huggingFaceAuth,
+ name: 'list_repo_files',
+ classification: 'SEARCH',
+ displayName: 'List Repo Files',
+ description: 'List the files and folders of a model, dataset or Space repository.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the files and folders under a path of a Hub repository at a revision, one page per call with a next_cursor; each entry carries its type, path, size and LFS info. Use it to discover file paths before Read Repo File or Get File/Folder Info; set Recursive to walk sub-folders. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listRepoFilesOutputSchema,
+ props: {
+ repo_type: hfProps.repoType(),
+ repo_id: hfProps.repoId(),
+ revision: hfProps.revision(),
+ path: Property.ShortText({
+ displayName: 'Folder Path',
+ description: "Folder inside the repository to list, for example 'onnx' or 'data/train'. Leave empty for the root.",
+ required: false,
+ }),
+ recursive: Property.Checkbox({
+ displayName: 'Recursive',
+ description: 'List every file in sub-folders too.',
+ required: false,
+ defaultValue: false,
+ }),
+ expand: Property.Checkbox({
+ displayName: 'Include Last Commit',
+ description: 'Add the last commit and security-scan status to each entry. Limits a page to 100 entries.',
+ required: false,
+ defaultValue: false,
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: 'Maximum entries in this page: up to 1000, or up to 100 when Include Last Commit is on.',
+ required: false,
+ }),
+ cursor: hfProps.cursor(),
+ },
+ async run(context) {
+ const { repo_type, repo_id, revision, path, recursive, expand, limit, cursor } = context.propsValue;
+ hfUtils.assertLimit({ value: limit, min: 1, max: expand ? 100 : 1000, name: 'Limit' });
+ const token = context.auth.secret_text;
+ const apiPath = await hfRepo.apiPath({ token, repoType: repo_type, repoId: repo_id });
+ const encodedPath = hfRepo.encodeFilePath(path);
+ const response = await hfHub.request<unknown>({
+ token,
+ method: HttpMethod.GET,
+ path: `${apiPath}/tree/${hfRepo.encodeRevision(revision)}${encodedPath ? `/${encodedPath}` : ''}`,
+ query: [
+ ['recursive', recursive ? 'true' : undefined],
+ ['expand', expand ? 'true' : undefined],
+ ['limit', limit],
+ ['cursor', cursor],
+ ],
+ });
+ const files = Array.isArray(response.body) ? response.body : [];
+ return {
+ files,
+ count: files.length,
+ next_cursor: hfHub.parseNextCursor(response.headers),
+ };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-repo-refs.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-repo-refs.ts
new file mode 100644
index 00000000000..60c20768033
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-repo-refs.ts
@@ -0,0 +1,44 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { listRepoRefsOutputSchema } from '../output-schemas';
+
+export const listRepoRefs = createAction({
+ auth: huggingFaceAuth,
+ name: 'list_repo_refs',
+ classification: 'SEARCH',
+ displayName: 'List Branches & Tags',
+ description: 'List the branches, tags and converted refs of a Hub repository.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Lists every git ref of a Hub repository: branches, tags, converted refs (such as 'refs/convert/parquet') and, optionally, pull-request refs ('refs/pr/N'), each with its target commit. Use it to find a valid revision before reading files, listing commits or comparing revisions. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: listRepoRefsOutputSchema,
+ props: {
+ repo_type: hfProps.repoType(),
+ repo_id: hfProps.repoId(),
+ include_prs: Property.Checkbox({
+ displayName: 'Include Pull Request Refs',
+ description: "Also list the 'refs/pr/N' refs of open and closed pull requests.",
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run(context) {
+ const { repo_type, repo_id, include_prs } = context.propsValue;
+ const token = context.auth.secret_text;
+ const apiPath = await hfRepo.apiPath({ token, repoType: repo_type, repoId: repo_id });
+ const response = await hfHub.request<unknown>({
+ token,
+ method: HttpMethod.GET,
+ path: `${apiPath}/refs`,
+ query: [['include_prs', include_prs ? '1' : undefined]],
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/list-trending-repos.ts b/packages/pieces/community/hugging-face/src/lib/actions/list-trending-repos.ts
new file mode 100644
index 00000000000..e376fe3e030
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/list-trending-repos.ts
@@ -0,0 +1,64 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfUtils } from '../common/utils';
+import { listTrendingReposOutputSchema } from '../output-schemas';
+
+export const listTrendingRepos = createAction({
+ auth: huggingFaceAuth,
+ name: 'list_trending_repos',
+ classification: 'SEARCH',
+ displayName: 'List Trending Repos',
+ description: 'List the repositories currently trending on the Hugging Face Hub.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the models, datasets and Spaces currently trending on the Hugging Face Hub (up to 20), each tagged with its repo_type. Use it to answer "what is popular right now"; for keyword or tag search use Search Models, Search Datasets or Search Spaces instead. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listTrendingReposOutputSchema,
+ props: {
+ type: Property.StaticDropdown({
+ displayName: 'Repository Type',
+ description: 'Only trending repositories of this type. Defaults to all types.',
+ required: false,
+ defaultValue: 'all',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'All', value: 'all' },
+ { label: 'Models', value: 'model' },
+ { label: 'Datasets', value: 'dataset' },
+ { label: 'Spaces', value: 'space' },
+ ],
+ },
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: 'Number of trending repositories to return (1 to 20). Defaults to 10.',
+ required: false,
+ defaultValue: 10,
+ }),
+ },
+ async run(context) {
+ const { type, limit } = context.propsValue;
+ hfUtils.assertLimit({ value: limit, min: 1, max: 20, name: 'Limit' });
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/api/trending',
+ query: [
+ ['type', type],
+ ['limit', limit],
+ ],
+ });
+ const body = response.body;
+ const items = hfHub.isRecord(body) && Array.isArray(body['recentlyTrending']) ? body['recentlyTrending'] : [];
+ const repos = items.filter(hfHub.isRecord).map((item) => {
+ const repoData = hfHub.isRecord(item['repoData']) ? item['repoData'] : {};
+ return { repo_type: item['repoType'] ?? null, ...repoData };
+ });
+ return { repos, count: repos.length };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/read-repo-file.ts b/packages/pieces/community/hugging-face/src/lib/actions/read-repo-file.ts
new file mode 100644
index 00000000000..da37f27a621
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/read-repo-file.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfRepo } from '../common/repo';
+import { readRepoFileOutputSchema } from '../output-schemas';
+
+export const readRepoFile = createAction({
+ auth: huggingFaceAuth,
+ name: 'read_repo_file',
+ classification: 'READ',
+ displayName: 'Read Repo File',
+ description: 'Read a text file (such as README.md or config.json) from a Hub repository.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Downloads one UTF-8 text file from a model, dataset or Space repository at a revision and returns its content, for example README.md, config.json or a training script. Files over 1 MiB or binary files (weights, images, parquet) fail with FILE_TOO_LARGE or BINARY_FILE and the download URL instead; check sizes first with Get File/Folder Info. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: readRepoFileOutputSchema,
+ props: {
+ repo_type: hfProps.repoType(),
+ repo_id: hfProps.repoId(),
+ path: Property.ShortText({
+ displayName: 'File Path',
+ description: "Path of the file inside the repository, for example 'README.md' or 'configs/config.json'.",
+ required: true,
+ }),
+ revision: hfProps.revision(),
+ },
+ async run(context) {
+ const { repo_type, repo_id, path, revision } = context.propsValue;
+ const encodedPath = hfRepo.encodeFilePath(path);
+ if (!encodedPath) {
+ throw new Error('File Path is required.');
+ }
+ const token = context.auth.secret_text;
+ const { resolvePrefix } = hfRepo.getTypeInfo(repo_type);
+ const canonicalId = await hfRepo.resolveRepoId({ token, repoType: repo_type, repoId: repo_id });
+ const resolvedRevision = revision?.trim() || 'main';
+ const url = `${hfHub.baseUrl}/${resolvePrefix}${hfRepo.encodeRepoId(canonicalId)}/resolve/${hfRepo.encodeRevision(resolvedRevision)}/${encodedPath}`;
+ const file = await hfHub.readRepoFileText({ token, url });
+ return {
+ repo_type,
+ repo_id: canonicalId,
+ revision: resolvedRevision,
+ path,
+ content: file.content,
+ size_bytes: file.sizeBytes,
+ url,
+ };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/search-datasets.ts b/packages/pieces/community/hugging-face/src/lib/actions/search-datasets.ts
new file mode 100644
index 00000000000..ebb3b4af000
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/search-datasets.ts
@@ -0,0 +1,100 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfUtils } from '../common/utils';
+import { searchDatasetsOutputSchema } from '../output-schemas';
+
+export const searchDatasets = createAction({
+ auth: huggingFaceAuth,
+ name: 'search_datasets',
+ classification: 'SEARCH',
+ displayName: 'Search Datasets',
+ description: 'Search and filter datasets on the Hugging Face Hub.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Searches Hugging Face Hub datasets by free text, author, tag filters and gating, returning one page of dataset summaries plus a next_cursor. Task filtering goes through Tag Filters (for example 'task_categories:text-classification'), not a pipeline field. Use Get Dataset for one dataset's metadata and Search Models or Search Spaces for other repo types. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: searchDatasetsOutputSchema,
+ props: {
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: "Free-text match on the dataset ID, for example 'imdb' or 'squad'.",
+ required: false,
+ }),
+ author: Property.ShortText({
+ displayName: 'Author',
+ description: "Only datasets owned by this user or organization, for example 'stanfordnlp'.",
+ required: false,
+ }),
+ filter: Property.Array({
+ displayName: 'Tag Filters',
+ description:
+ "Hub tags every result must carry, for example 'task_categories:text-classification', 'language:en' or 'size_categories:10K<n<100K'. Discover valid values with List Hub Tags by Type.",
+ required: false,
+ }),
+ gated: Property.StaticDropdown({
+ displayName: 'Gated',
+ description: 'Only gated datasets, only non-gated datasets, or leave empty for both.',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Only gated', value: 'true' },
+ { label: 'Only not gated', value: 'false' },
+ ],
+ },
+ }),
+ sort: Property.StaticDropdown({
+ displayName: 'Sort By',
+ description: 'Sort order (always descending). Defaults to trending.',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Trending', value: 'trendingScore' },
+ { label: 'Downloads', value: 'downloads' },
+ { label: 'Likes', value: 'likes' },
+ { label: 'Recently Created', value: 'createdAt' },
+ { label: 'Recently Updated', value: 'lastModified' },
+ ],
+ },
+ }),
+ limit: hfProps.limit({ defaultValue: 20, max: 1000 }),
+ full: Property.Checkbox({
+ displayName: 'Include Full Details',
+ description: 'Return extra fields such as the card data and file list for each dataset.',
+ required: false,
+ defaultValue: false,
+ }),
+ cursor: hfProps.cursor(),
+ },
+ async run(context) {
+ const { search, author, filter, gated, sort, limit, full, cursor } = context.propsValue;
+ hfUtils.assertLimit({ value: limit, min: 1, max: 1000, name: 'Limit' });
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/api/datasets',
+ query: [
+ ['search', search],
+ ['author', author],
+ ...hfUtils.toStringArray(filter).map((tag): [string, string] => ['filter', tag]),
+ ['gated', hfUtils.booleanFlag(gated)],
+ ['sort', sort],
+ ['limit', limit],
+ ['full', full ? 'true' : undefined],
+ ['cursor', cursor],
+ ],
+ });
+ const datasets = Array.isArray(response.body) ? response.body : [];
+ return {
+ datasets,
+ count: datasets.length,
+ next_cursor: hfHub.parseNextCursor(response.headers),
+ };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/search-models.ts b/packages/pieces/community/hugging-face/src/lib/actions/search-models.ts
new file mode 100644
index 00000000000..58b08a7ae05
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/search-models.ts
@@ -0,0 +1,101 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfUtils } from '../common/utils';
+import { searchModelsOutputSchema } from '../output-schemas';
+
+export const searchModels = createAction({
+ auth: huggingFaceAuth,
+ name: 'search_models',
+ classification: 'SEARCH',
+ displayName: 'Search Models',
+ description: 'Search and filter models on the Hugging Face Hub.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Searches the Hugging Face Hub model catalogue by free text, author, tag filters, pipeline task and Inference Provider availability, returning one page of model summaries plus a next_cursor. Use it to find a model ID before calling Get Model, Generate Chat Completion (pipeline_tag 'text-generation', inference_provider 'all') or Generate Text Embeddings (pipeline_tag 'feature-extraction'); use Search Datasets or Search Spaces for other repo types. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: searchModelsOutputSchema,
+ props: {
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: "Free-text match on the model ID, for example 'llama' or 'bert-base'.",
+ required: false,
+ }),
+ author: Property.ShortText({
+ displayName: 'Author',
+ description: "Only models owned by this user or organization, for example 'meta-llama'.",
+ required: false,
+ }),
+ filter: Property.Array({
+ displayName: 'Tag Filters',
+ description:
+ "Hub tags every result must carry, for example 'text-classification', 'pytorch', 'license:apache-2.0' or 'language:en'. Discover valid values with List Hub Tags by Type.",
+ required: false,
+ }),
+ pipeline_tag: Property.ShortText({
+ displayName: 'Pipeline Task',
+ description: "Only models for this task, for example 'text-generation', 'feature-extraction' or 'image-classification'.",
+ required: false,
+ }),
+ inference_provider: Property.ShortText({
+ displayName: 'Inference Provider',
+ description:
+ "Only models served by Inference Providers: 'all' for any provider, or one provider name such as 'groq', 'together' or 'hf-inference'.",
+ required: false,
+ }),
+ sort: Property.StaticDropdown({
+ displayName: 'Sort By',
+ description: 'Sort order (always descending). Defaults to trending.',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Trending', value: 'trendingScore' },
+ { label: 'Downloads', value: 'downloads' },
+ { label: 'Likes', value: 'likes' },
+ { label: 'Recently Created', value: 'createdAt' },
+ { label: 'Recently Updated', value: 'lastModified' },
+ ],
+ },
+ }),
+ limit: hfProps.limit({ defaultValue: 20, max: 1000 }),
+ full: Property.Checkbox({
+ displayName: 'Include Full Details',
+ description: 'Return extra fields such as the file list and last-modified date for each model.',
+ required: false,
+ defaultValue: false,
+ }),
+ cursor: hfProps.cursor(),
+ },
+ async run(context) {
+ const { search, author, filter, pipeline_tag, inference_provider, sort, limit, full, cursor } =
+ context.propsValue;
+ hfUtils.assertLimit({ value: limit, min: 1, max: 1000, name: 'Limit' });
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/api/models',
+ query: [
+ ['search', search],
+ ['author', author],
+ ...hfUtils.toStringArray(filter).map((tag): [string, string] => ['filter', tag]),
+ ['pipeline_tag', pipeline_tag],
+ ['inference_provider', inference_provider],
+ ['sort', sort],
+ ['limit', limit],
+ ['full', full ? 'true' : undefined],
+ ['cursor', cursor],
+ ],
+ });
+ const models = Array.isArray(response.body) ? response.body : [];
+ return {
+ models,
+ count: models.length,
+ next_cursor: hfHub.parseNextCursor(response.headers),
+ };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/search-papers.ts b/packages/pieces/community/hugging-face/src/lib/actions/search-papers.ts
new file mode 100644
index 00000000000..bbbdca7f56b
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/search-papers.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfUtils } from '../common/utils';
+import { searchPapersOutputSchema } from '../output-schemas';
+
+export const searchPapers = createAction({
+ auth: huggingFaceAuth,
+ name: 'search_papers',
+ classification: 'SEARCH',
+ displayName: 'Search Papers',
+ description: 'Search research papers indexed on Hugging Face.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Searches the research papers indexed on Hugging Face Papers with a hybrid semantic and full-text query, returning up to 120 matches with their arXiv-style IDs, titles, authors and summaries. Use it to find papers on a topic; use List Daily Papers for what was featured on a given day and Get Paper for one paper's full details. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: searchPapersOutputSchema,
+ props: {
+ query: Property.ShortText({
+ displayName: 'Query',
+ description: "What to search for, up to 250 characters, for example 'retrieval augmented generation'.",
+ required: true,
+ }),
+ limit: hfProps.limit({ defaultValue: 20, max: 120 }),
+ },
+ async run(context) {
+ const { query, limit } = context.propsValue;
+ hfUtils.assertLimit({ value: limit, min: 1, max: 120, name: 'Limit' });
+ const trimmed = query.trim();
+ if (trimmed.length === 0 || trimmed.length > 250) {
+ throw new Error('Query must be between 1 and 250 characters.');
+ }
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/api/papers/search',
+ query: [
+ ['q', trimmed],
+ ['limit', limit],
+ ],
+ });
+ const papers = Array.isArray(response.body) ? response.body : [];
+ return { papers, count: papers.length };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/search-spaces.ts b/packages/pieces/community/hugging-face/src/lib/actions/search-spaces.ts
new file mode 100644
index 00000000000..023f37aa9a8
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/actions/search-spaces.ts
@@ -0,0 +1,85 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { huggingFaceAuth } from '../auth';
+import { hfHub } from '../common/hub-client';
+import { hfProps } from '../common/props';
+import { hfUtils } from '../common/utils';
+import { searchSpacesOutputSchema } from '../output-schemas';
+
+export const searchSpaces = createAction({
+ auth: huggingFaceAuth,
+ name: 'search_spaces',
+ classification: 'SEARCH',
+ displayName: 'Search Spaces',
+ description: 'Search and filter Spaces (hosted ML apps) on the Hugging Face Hub.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Searches Hugging Face Spaces (hosted Gradio, Docker or static ML apps) by free text, author and tag filters, returning one page of Space summaries plus a next_cursor. Use Get Space for one Space's SDK, hardware and runtime stage; use Search Models or Search Datasets for other repo types. Read-only and safe to retry.",
+ idempotent: true,
+ },
+ outputSchema: searchSpacesOutputSchema,
+ props: {
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: "Free-text match on the Space ID, for example 'whisper' or 'chatbot'.",
+ required: false,
+ }),
+ author: Property.ShortText({
+ displayName: 'Author',
+ description: "Only Spaces owned by this user or organization, for example 'huggingface'.",
+ required: false,
+ }),
+ filter: Property.Array({
+ displayName: 'Tag Filters',
+ description: "Hub tags every result must carry, for example 'gradio', 'docker' or 'region:us'.",
+ required: false,
+ }),
+ sort: Property.StaticDropdown({
+ displayName: 'Sort By',
+ description: 'Sort order (always descending). Defaults to trending.',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Trending', value: 'trendingScore' },
+ { label: 'Likes', value: 'likes' },
+ { label: 'Recently Created', value: 'createdAt' },
+ { label: 'Recently Updated', value: 'lastModified' },
+ ],
+ },
+ }),
+ limit: hfProps.limit({ defaultValue: 20, max: 1000 }),
+ full: Property.Checkbox({
+ displayName: 'Include Full Details',
+ description: 'Return extra fields such as the card data and file list for each Space.',
+ required: false,
+ defaultValue: false,
+ }),
+ cursor: hfProps.cursor(),
+ },
+ async run(context) {
+ const { search, author, filter, sort, limit, full, cursor } = context.propsValue;
+ hfUtils.assertLimit({ value: limit, min: 1, max: 1000, name: 'Limit' });
+ const response = await hfHub.request<unknown>({
+ token: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/api/spaces',
+ query: [
+ ['search', search],
+ ['author', author],
+ ...hfUtils.toStringArray(filter).map((tag): [string, string] => ['filter', tag]),
+ ['sort', sort],
+ ['limit', limit],
+ ['full', full ? 'true' : undefined],
+ ['cursor', cursor],
+ ],
+ });
+ const spaces = Array.isArray(response.body) ? response.body : [];
+ return {
+ spaces,
+ count: spaces.length,
+ next_cursor: hfHub.parseNextCursor(response.headers),
+ };
+ },
+});
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/text-classification.ts b/packages/pieces/community/hugging-face/src/lib/actions/text-classification.ts
index dd26364dd0f..2728ae406ee 100644
--- a/packages/pieces/community/hugging-face/src/lib/actions/text-classification.ts
+++ b/packages/pieces/community/hugging-face/src/lib/actions/text-classification.ts
@@ -18,7 +18,7 @@ export const textClassification = createAction({
'Classify text into categories using Hugging Face models - includes zero-shot classification for custom categories',
aiMetadata: {
description:
- 'Scores a block of text against a set of labels and returns the ranked predictions, in one of three modes: zero-shot classifies into custom comma-separated categories you supply, pre-trained uses a curated sentiment, emotion, or topic model with its own fixed label set, and search runs any classification model looked up on the Hugging Face hub. Choose it to sort text into a known label set - use chat_completion for open-ended reasoning about the text, text_summarization to condense it, and image_classification when the input is an image rather than text. Zero-shot mode fails without at least one category; read-only and idempotent, as classifying stores nothing.',
+ 'Scores a block of text against a set of labels and returns the ranked predictions, in one of three modes: zero-shot classifies into custom comma-separated categories you supply, pre-trained uses a curated sentiment, emotion, or topic model with its own fixed label set, and search runs any classification model looked up on the Hugging Face hub. Choose it to sort text into a known label set - use generate_chat_completion for open-ended reasoning about the text, text_summarization to condense it, and image_classification when the input is an image rather than text. Zero-shot mode fails without at least one category; read-only and idempotent, as classifying stores nothing.',
idempotent: true,
},
outputSchema: textClassificationOutputSchema,
diff --git a/packages/pieces/community/hugging-face/src/lib/actions/text-summarization.ts b/packages/pieces/community/hugging-face/src/lib/actions/text-summarization.ts
index 13ba67996be..c6778b9a151 100644
--- a/packages/pieces/community/hugging-face/src/lib/actions/text-summarization.ts
+++ b/packages/pieces/community/hugging-face/src/lib/actions/text-summarization.ts
@@ -14,7 +14,7 @@ export const textSummarization = createAction({
'Generate abstractive summaries of long text using Hugging Face models - optimized for business content',
aiMetadata: {
description:
- 'Condenses one long block of text into a shorter abstractive summary with a Hugging Face summarization model such as BART or Pegasus, targeting either a brief, medium, or detailed length preset or explicit min and max token counts. Choose it over chat_completion when the task is purely summarization, since it decodes greedily for stable output; use text_classification to label the text instead, or language_translation to change its language. Works best on inputs of roughly 512 to 1024 tokens and needs a truncation strategy for anything longer; read-only and idempotent, as it stores nothing.',
+ 'Condenses one long block of text into a shorter abstractive summary with a Hugging Face summarization model such as BART or Pegasus, targeting either a brief, medium, or detailed length preset or explicit min and max token counts. Choose it over generate_chat_completion when the task is purely summarization, since it decodes greedily for stable output; use text_classification to label the text instead, or language_translation to change its language. Works best on inputs of roughly 512 to 1024 tokens and needs a truncation strategy for anything longer; read-only and idempotent, as it stores nothing.',
idempotent: true,
},
outputSchema: textSummarizationOutputSchema,
diff --git a/packages/pieces/community/hugging-face/src/lib/common/hub-client.ts b/packages/pieces/community/hugging-face/src/lib/common/hub-client.ts
new file mode 100644
index 00000000000..c96102e2dd5
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/common/hub-client.ts
@@ -0,0 +1,279 @@
+import { Readable } from 'node:stream';
+import {
+ AuthenticationType,
+ httpClient,
+ HttpError,
+ HttpHeaders,
+ HttpMethod,
+ HttpResponse,
+} from '@activepieces/pieces-common';
+
+function buildUrl({ baseUrl, path, query }: BuildUrlParams): string {
+ const search = new URLSearchParams();
+ for (const [key, value] of query ?? []) {
+ if (value === undefined || value === null || value === '') {
+ continue;
+ }
+ search.append(key, String(value));
+ }
+ const queryString = search.toString();
+ return queryString ? `${baseUrl}${path}?${queryString}` : `${baseUrl}${path}`;
+}
+
+async function hubRequest<T>({
+ token,
+ method,
+ path,
+ query,
+ body,
+ baseUrl,
+ anonymous,
+}: HubRequestParams): Promise<HttpResponse<T>> {
+ const url = buildUrl({ baseUrl: baseUrl ?? HUB_BASE_URL, path, query });
+ try {
+ return await httpClient.sendRequest<T>({
+ method,
+ url,
+ body,
+ authentication: anonymous ? undefined : { type: AuthenticationType.BEARER_TOKEN, token },
+ });
+ } catch (error) {
+ throw toHubError({ error, resource: path });
+ }
+}
+
+function extractErrorDetail(body: unknown): string | null {
+ if (typeof body === 'string') {
+ const trimmed = body.trim();
+ return trimmed.length > 0 ? trimmed.slice(0, 500) : null;
+ }
+ if (isRecord(body)) {
+ const error = body['error'];
+ if (typeof error === 'string') {
+ return error;
+ }
+ const message = body['message'];
+ if (typeof message === 'string') {
+ return message;
+ }
+ }
+ return null;
+}
+
+function rateLimitError(detail: string | null): Error {
+ const match = detail?.match(/t=(\d+)/);
+ const resetHint = match
+ ? `Retry after about ${match[1]} seconds.`
+ : 'Hub limits reset on fixed 5-minute windows, so retry in a few minutes.';
+ return new Error(
+ `Hugging Face rate limit reached (429). ${resetHint}${detail ? ` Details: ${detail}` : ''}`
+ );
+}
+
+function toHubError({ error, resource }: ToHubErrorParams): Error {
+ if (!(error instanceof HttpError)) {
+ return error instanceof Error ? error : new Error(String(error));
+ }
+ const status = error.response.status;
+ const detail = extractErrorDetail(error.response.body);
+ const suffix = detail ? ` Details: ${detail}` : '';
+ switch (status) {
+ case 400:
+ case 422:
+ return new Error(`Hugging Face rejected the request (${status}) for ${resource}.${suffix}`);
+ case 401:
+ return new Error(
+ `Hugging Face rejected the access token (401) for ${resource}. Check that the connection's token is valid and has not been revoked; private or gated repositories also answer 401 when the token cannot see them.${suffix}`
+ );
+ case 403:
+ return new Error(
+ `Access denied (403) for ${resource}. The token lacks permission for this resource (a fine-grained token may not cover it), or the repository is gated and this account has not been granted access.${suffix}`
+ );
+ case 404:
+ return new Error(
+ `Not found (404): ${resource}. Check the repository type, ID, revision and path; private repositories are only visible to tokens that can access them.${suffix}`
+ );
+ case 429:
+ return rateLimitError(detail);
+ default:
+ return new Error(`Hugging Face request failed (${status}) for ${resource}.${suffix}`);
+ }
+}
+
+function readHeader({ headers, name }: ReadHeaderParams): string | null {
+ const value = headers?.[name.toLowerCase()];
+ if (value === undefined) {
+ return null;
+ }
+ return Array.isArray(value) ? value.join(', ') : value;
+}
+
+function parseNextLinkParam({ headers, param }: ParseNextLinkParams): string | null {
+ const link = readHeader({ headers, name: 'link' });
+ if (!link) {
+ return null;
+ }
+ const match = link.match(/<([^>]+)>\s*;\s*rel="?next"?/);
+ if (!match) {
+ return null;
+ }
+ return new URL(match[1], HUB_BASE_URL).searchParams.get(param);
+}
+
+function parseNextCursor(headers: HttpHeaders | undefined): string | null {
+ return parseNextLinkParam({ headers, param: 'cursor' });
+}
+
+async function readStreamWithCap({ stream, maxBytes }: ReadStreamParams): Promise<Buffer | null> {
+ const chunks: Buffer[] = [];
+ let total = 0;
+ for await (const chunk of stream) {
+ const buffer: Buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ total += buffer.length;
+ if (total > maxBytes) {
+ stream.destroy();
+ return null;
+ }
+ chunks.push(buffer);
+ }
+ return Buffer.concat(chunks);
+}
+
+function oversizeError({ url, size }: { url: string; size: number | null }): Error {
+ const sizeText = size === null ? `more than ${MAX_TEXT_FILE_BYTES} bytes` : `${size} bytes`;
+ return new Error(
+ `FILE_TOO_LARGE: the file is ${sizeText}, above the ${MAX_TEXT_FILE_BYTES}-byte limit for Read Repo File. Download it directly instead: ${url}`
+ );
+}
+
+function binaryError(url: string): Error {
+ return new Error(
+ `BINARY_FILE: the file is not UTF-8 text, so Read Repo File cannot return it. Download it directly instead: ${url}`
+ );
+}
+
+function decodeText(buffer: Buffer): string | null {
+ if (buffer.subarray(0, 8000).includes(0)) {
+ return null;
+ }
+ try {
+ return new TextDecoder('utf-8', { fatal: true }).decode(buffer);
+ } catch {
+ return null;
+ }
+}
+
+async function readRepoFileText({ token, url }: ReadRepoFileParams): Promise<RepoFileText> {
+ let currentUrl = url;
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
+ const sendAuth = new URL(currentUrl).host === HUB_HOST;
+ let response: HttpResponse<Readable>;
+ try {
+ response = await httpClient.sendRequest<Readable>({
+ method: HttpMethod.GET,
+ url: currentUrl,
+ followRedirects: false,
+ responseType: 'stream',
+ authentication: sendAuth ? { type: AuthenticationType.BEARER_TOKEN, token } : undefined,
+ });
+ } catch (error) {
+ throw toHubError({ error, resource: new URL(currentUrl).pathname });
+ }
+ if (response.status >= 300 && response.status < 400) {
+ response.body.destroy();
+ const linkedSize = Number(readHeader({ headers: response.headers, name: 'x-linked-size' }));
+ if (Number.isFinite(linkedSize) && linkedSize > MAX_TEXT_FILE_BYTES) {
+ throw oversizeError({ url, size: linkedSize });
+ }
+ const location = readHeader({ headers: response.headers, name: 'location' });
+ if (!location) {
+ throw new Error(`Hugging Face answered ${response.status} without a redirect target for ${url}`);
+ }
+ currentUrl = new URL(location, currentUrl).toString();
+ continue;
+ }
+ const declaredLength = Number(readHeader({ headers: response.headers, name: 'content-length' }));
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_TEXT_FILE_BYTES) {
+ response.body.destroy();
+ throw oversizeError({ url, size: declaredLength });
+ }
+ const buffer = await readStreamWithCap({ stream: response.body, maxBytes: MAX_TEXT_FILE_BYTES });
+ if (buffer === null) {
+ throw oversizeError({ url, size: null });
+ }
+ const content = decodeText(buffer);
+ if (content === null) {
+ throw binaryError(url);
+ }
+ return { content, sizeBytes: buffer.length };
+ }
+ throw new Error(`Too many redirects while downloading ${url}`);
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+const HUB_HOST = 'huggingface.co';
+const HUB_BASE_URL = `https://${HUB_HOST}`;
+const MAX_TEXT_FILE_BYTES = 1024 * 1024;
+const MAX_REDIRECTS = 5;
+
+export const hfHub = {
+ baseUrl: HUB_BASE_URL,
+ maxTextFileBytes: MAX_TEXT_FILE_BYTES,
+ request: hubRequest,
+ toError: toHubError,
+ parseNextCursor,
+ parseNextLinkParam,
+ readRepoFileText,
+ isRecord,
+};
+
+export type QueryEntry = [string, string | number | boolean | undefined | null];
+
+type BuildUrlParams = {
+ baseUrl: string;
+ path: string;
+ query?: QueryEntry[];
+};
+
+type HubRequestParams = {
+ token: string;
+ method: HttpMethod;
+ path: string;
+ query?: QueryEntry[];
+ body?: unknown;
+ baseUrl?: string;
+ anonymous?: boolean;
+};
+
+type ToHubErrorParams = {
+ error: unknown;
+ resource: string;
+};
+
+type ReadHeaderParams = {
+ headers: HttpHeaders | undefined;
+ name: string;
+};
+
+type ParseNextLinkParams = {
+ headers: HttpHeaders | undefined;
+ param: string;
+};
+
+type ReadStreamParams = {
+ stream: Readable;
+ maxBytes: number;
+};
+
+type ReadRepoFileParams = {
+ token: string;
+ url: string;
+};
+
+type RepoFileText = {
+ content: string;
+ sizeBytes: number;
+};
diff --git a/packages/pieces/community/hugging-face/src/lib/common/inference.ts b/packages/pieces/community/hugging-face/src/lib/common/inference.ts
new file mode 100644
index 00000000000..2461e6fabc9
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/common/inference.ts
@@ -0,0 +1,132 @@
+import { Property } from '@activepieces/pieces-framework';
+import {
+ InferenceClientHubApiError,
+ InferenceClientInputError,
+ InferenceClientProviderApiError,
+ InferenceProviderOrPolicy,
+ PROVIDERS_OR_POLICIES,
+} from '@huggingface/inference';
+
+function findProvider(value: string): InferenceProviderOrPolicy | undefined {
+ return PROVIDERS_OR_POLICIES.find((provider) => provider === value);
+}
+
+function resolveModelAndProvider({ model, provider, defaultModel }: ResolveModelParams): ResolvedModel {
+ const trimmed = (model ?? '').trim() || (defaultModel ?? '');
+ if (trimmed.length === 0) {
+ throw new Error('Model is required.');
+ }
+ const selected = provider ? findProvider(provider) : undefined;
+ if (provider && !selected) {
+ throw new Error(`Unknown inference provider '${provider}'. Use one of: ${PROVIDERS_OR_POLICIES.join(', ')}.`);
+ }
+ const colon = trimmed.lastIndexOf(':');
+ if (colon <= 0) {
+ return { model: trimmed, provider: selected };
+ }
+ const baseModel = trimmed.slice(0, colon);
+ const suffix = trimmed.slice(colon + 1).trim();
+ if (suffix === 'fastest' || suffix === 'cheapest') {
+ throw new Error(
+ `The ':${suffix}' routing policy is not supported by this action. Remove the suffix to use your provider preference order, or pick a provider explicitly.`
+ );
+ }
+ const suffixProvider = suffix === 'preferred' ? 'auto' : findProvider(suffix);
+ if (!suffixProvider) {
+ throw new Error(
+ `Unknown provider suffix ':${suffix}' on model '${trimmed}'. Use one of: ${PROVIDERS_OR_POLICIES.join(', ')}, or ':preferred'.`
+ );
+ }
+ if (selected && selected !== suffixProvider) {
+ throw new Error(
+ `The model suffix ':${suffix}' conflicts with the selected provider '${selected}'. Set only one of them.`
+ );
+ }
+ return { model: baseModel, provider: suffixProvider };
+}
+
+function toInferenceError(error: unknown): Error {
+ if (error instanceof InferenceClientProviderApiError || error instanceof InferenceClientHubApiError) {
+ const status = error.httpResponse.status;
+ switch (status) {
+ case 401:
+ return new Error(
+ `Hugging Face rejected the token for inference (401). Use a valid token; fine-grained tokens need the "Make calls to Inference Providers" permission. ${error.message}`
+ );
+ case 402:
+ return new Error(
+ `Inference Providers credits are exhausted (402). Add credits or a payment method in your Hugging Face billing settings. ${error.message}`
+ );
+ case 403:
+ return new Error(
+ `Access denied for inference (403). The token lacks inference permission, or the model is gated and this account has not been granted access. ${error.message}`
+ );
+ case 404:
+ return new Error(
+ `Model not found or not served by the chosen provider (404). Find a served model with Search Models (inference_provider 'all'). ${error.message}`
+ );
+ case 429:
+ return new Error(`Inference rate limit reached (429). Retry in a few minutes. ${error.message}`);
+ default:
+ return new Error(`Inference request failed (${status}). ${error.message}`);
+ }
+ }
+ if (error instanceof InferenceClientInputError) {
+ return new Error(error.message);
+ }
+ return error instanceof Error ? error : new Error(String(error));
+}
+
+function providerProp() {
+ return Property.StaticDropdown({
+ displayName: 'Provider',
+ description:
+ "Inference provider to run the model on. Leave empty (or 'auto') to use the first available provider in your Hugging Face provider preference order.",
+ required: false,
+ options: {
+ disabled: false,
+ options: PROVIDERS_OR_POLICIES.map((provider) => ({
+ label: provider === 'auto' ? 'Auto (your preference order)' : provider,
+ value: provider,
+ })),
+ },
+ });
+}
+
+function optionalBooleanProp({ displayName, description }: OptionalBooleanParams) {
+ return Property.StaticDropdown({
+ displayName,
+ description,
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Yes', value: 'true' },
+ { label: 'No', value: 'false' },
+ ],
+ },
+ });
+}
+
+export const hfInference = {
+ resolveModelAndProvider,
+ toError: toInferenceError,
+ providerProp,
+ optionalBooleanProp,
+};
+
+type ResolveModelParams = {
+ model: string | undefined;
+ provider: string | undefined;
+ defaultModel?: string;
+};
+
+type ResolvedModel = {
+ model: string;
+ provider: InferenceProviderOrPolicy | undefined;
+};
+
+type OptionalBooleanParams = {
+ displayName: string;
+ description: string;
+};
diff --git a/packages/pieces/community/hugging-face/src/lib/common/props.ts b/packages/pieces/community/hugging-face/src/lib/common/props.ts
new file mode 100644
index 00000000000..09f8191f634
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/common/props.ts
@@ -0,0 +1,88 @@
+import { Property } from '@activepieces/pieces-framework';
+
+function repoType() {
+ return Property.StaticDropdown({
+ displayName: 'Repository Type',
+ description: "The kind of Hub repository: 'model', 'dataset' or 'space'.",
+ required: true,
+ defaultValue: 'model',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Model', value: 'model' },
+ { label: 'Dataset', value: 'dataset' },
+ { label: 'Space', value: 'space' },
+ ],
+ },
+ });
+}
+
+function repoId() {
+ return Property.ShortText({
+ displayName: 'Repository ID',
+ description:
+ "The repository ID in 'namespace/name' form, for example 'openai-community/gpt2' or 'stanfordnlp/imdb'. Find it with Search Models, Search Datasets or Search Spaces.",
+ required: true,
+ });
+}
+
+function revision() {
+ return Property.ShortText({
+ displayName: 'Revision',
+ description:
+ "Branch, tag, or commit SHA to read, for example 'main', 'v1.0' or 'refs/pr/1'. Defaults to 'main'. List available refs with List Branches & Tags.",
+ required: false,
+ defaultValue: 'main',
+ });
+}
+
+function optionalRevision() {
+ return Property.ShortText({
+ displayName: 'Revision',
+ description:
+ "Optional branch, tag, or commit SHA, for example 'main' or 'refs/pr/1'. Leave empty for the default branch.",
+ required: false,
+ });
+}
+
+function cursor() {
+ return Property.ShortText({
+ displayName: 'Cursor',
+ description:
+ "The 'next_cursor' value returned by a previous call, to fetch the next page. Leave empty for the first page.",
+ required: false,
+ });
+}
+
+function limit({ defaultValue, max }: LimitParams) {
+ return Property.Number({
+ displayName: 'Limit',
+ description: `Maximum number of results in this page (1 to ${max}).`,
+ required: false,
+ defaultValue,
+ });
+}
+
+function page() {
+ return Property.Number({
+ displayName: 'Page',
+ description: 'Zero-based page number. Use 0 for the first page, then the returned next_page value.',
+ required: false,
+ defaultValue: 0,
+ });
+}
+
+export const hfProps = {
+ repoType,
+ repoId,
+ revision,
+ optionalRevision,
+ cursor,
+ limit,
+ page,
+};
+
+type LimitParams = {
+ defaultValue: number;
+ max: number;
+};
diff --git a/packages/pieces/community/hugging-face/src/lib/common/repo.ts b/packages/pieces/community/hugging-face/src/lib/common/repo.ts
new file mode 100644
index 00000000000..f885c8bc738
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/common/repo.ts
@@ -0,0 +1,93 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { hfHub } from './hub-client';
+
+function getRepoTypeInfo(repoType: string): RepoTypeInfo {
+ switch (repoType) {
+ case 'model':
+ return { apiSegment: 'models', resolvePrefix: '', singular: 'model' };
+ case 'dataset':
+ return { apiSegment: 'datasets', resolvePrefix: 'datasets/', singular: 'dataset' };
+ case 'space':
+ return { apiSegment: 'spaces', resolvePrefix: 'spaces/', singular: 'space' };
+ default:
+ throw new Error(`Unknown repository type '${repoType}'. Use one of: model, dataset, space.`);
+ }
+}
+
+function splitRepoId(repoId: string): string[] {
+ const segments = repoId
+ .trim()
+ .replace(/^\/+|\/+$/g, '')
+ .split('/')
+ .filter((segment) => segment.length > 0);
+ if (segments.length < 1 || segments.length > 2) {
+ throw new Error(
+ `Invalid repository ID '${repoId}'. Use the 'namespace/name' form, for example 'openai-community/gpt2'.`
+ );
+ }
+ return segments;
+}
+
+function encodeRepoId(repoId: string): string {
+ return splitRepoId(repoId).map(encodeURIComponent).join('/');
+}
+
+function encodeRevision(revision: string | undefined): string {
+ const value = revision?.trim();
+ return encodeURIComponent(value && value.length > 0 ? value : 'main');
+}
+
+function encodeFilePath(path: string | undefined): string {
+ return (path ?? '')
+ .split('/')
+ .filter((segment) => segment.length > 0)
+ .map(encodeURIComponent)
+ .join('/');
+}
+
+async function resolveRepoId({ token, repoType, repoId }: RepoRefParams): Promise<string> {
+ const segments = splitRepoId(repoId);
+ if (segments.length === 2) {
+ return segments.join('/');
+ }
+ const { apiSegment } = getRepoTypeInfo(repoType);
+ const response = await hfHub.request<{ id?: unknown }>({
+ token,
+ method: HttpMethod.GET,
+ path: `/api/${apiSegment}/${encodeURIComponent(segments[0])}`,
+ });
+ const canonical = response.body?.id;
+ if (typeof canonical !== 'string' || !canonical.includes('/')) {
+ throw new Error(
+ `Could not resolve the legacy repository ID '${repoId}' to its 'namespace/name' form. Pass the full ID instead.`
+ );
+ }
+ return canonical;
+}
+
+async function repoApiPath({ token, repoType, repoId }: RepoRefParams): Promise<string> {
+ const { apiSegment } = getRepoTypeInfo(repoType);
+ const canonical = await resolveRepoId({ token, repoType, repoId });
+ return `/api/${apiSegment}/${encodeRepoId(canonical)}`;
+}
+
+export const hfRepo = {
+ getTypeInfo: getRepoTypeInfo,
+ encodeRepoId,
+ encodeRevision,
+ encodeFilePath,
+ resolveRepoId,
+ apiPath: repoApiPath,
+};
+
+export type RepoTypeInfo = {
+ apiSegment: 'models' | 'datasets' | 'spaces';
+ resolvePrefix: '' | 'datasets/' | 'spaces/';
+ singular: 'model' | 'dataset' | 'space';
+};
+
+type RepoRefParams = {
+ token: string;
+ repoType: string;
+ repoId: string;
+};
diff --git a/packages/pieces/community/hugging-face/src/lib/common/utils.ts b/packages/pieces/community/hugging-face/src/lib/common/utils.ts
new file mode 100644
index 00000000000..6bf781b6c10
--- /dev/null
+++ b/packages/pieces/community/hugging-face/src/lib/common/utils.ts
@@ -0,0 +1,60 @@
+function truncateText({ text, maxChars }: TruncateTextParams): TruncatedText {
+ if (text.length <= maxChars) {
+ return { text, truncated: false, originalLength: text.length };
+ }
+ return { text: text.slice(0, maxChars), truncated: true, originalLength: text.length };
+}
+
+function toStringArray(value: unknown): string[] {
+ if (!Array.isArray(value)) {
+ return [];
+ }
+ return value
+ .filter((item): item is string | number => typeof item === 'string' || typeof item === 'number')
+ .map((item) => String(item).trim())
+ .filter((item) => item.length > 0);
+}
+
+function assertLimit({ value, min, max, name }: AssertLimitParams): void {
+ if (value === undefined) {
+ return;
+ }
+ if (!Number.isInteger(value) || value < min || value > max) {
+ throw new Error(`${name} must be a whole number between ${min} and ${max}.`);
+ }
+}
+
+function booleanFlag(value: string | undefined): boolean | undefined {
+ if (value === 'true') {
+ return true;
+ }
+ if (value === 'false') {
+ return false;
+ }
+ return undefined;
+}
+
+export const hfUtils = {
+ truncateText,
+ toStringArray,
+ assertLimit,
+ booleanFlag,
+};
+
+type TruncateTextParams = {
+ text: string;
+ maxChars: number;
+};
+
+type TruncatedText = {
+ text: string;
+ truncated: boolean;
+ originalLength: number;
+};
+
+type AssertLimitParams = {
+ value: number | undefined;
+ min: number;
+ max: number;
+ name: string;
+};
diff --git a/packages/pieces/community/hugging-face/src/lib/output-schemas.ts b/packages/pieces/community/hugging-face/src/lib/output-schemas.ts
index d76154dd6c0..681de61f716 100644
--- a/packages/pieces/community/hugging-face/src/lib/output-schemas.ts
+++ b/packages/pieces/community/hugging-face/src/lib/output-schemas.ts
@@ -11,6 +11,175 @@ const scoredLabelItems: OutputSchemaField[] = [
{ key: 'score', label: 'Score', format: 'number' },
];
+const nextCursorField: OutputSchemaField = {
+ key: 'next_cursor',
+ label: 'Next Cursor',
+ description: 'Pass this to Cursor to fetch the next page. Null on the last page.',
+};
+
+const nextPageField: OutputSchemaField = {
+ key: 'next_page',
+ label: 'Next Page',
+ format: 'number',
+ description: 'Pass this to Page to fetch the next page. Null on the last page.',
+};
+
+const countField: OutputSchemaField = { key: 'count', label: 'Count', format: 'number' };
+
+const pageField: OutputSchemaField = { key: 'page', label: 'Page', format: 'number' };
+
+const gatedField: OutputSchemaField = {
+ key: 'gated',
+ label: 'Gated',
+ description: "false, or the gating mode such as 'auto' or 'manual'.",
+};
+
+const hubAccountFields: OutputSchemaField[] = [
+ { key: 'name', label: 'Username' },
+ { key: 'fullname', label: 'Full Name' },
+ { key: 'type', label: 'Account Type' },
+];
+
+const repoSearchCoreFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Repo ID' },
+ { key: 'likes', label: 'Likes', format: 'number' },
+ { key: 'trendingScore', label: 'Trending Score', format: 'number' },
+ { key: 'private', label: 'Private', format: 'boolean' },
+ { key: 'tags', label: 'Tags' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+];
+
+const repoCardBaseFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Repo ID' },
+ { key: 'author', label: 'Author' },
+ { key: 'likes', label: 'Likes', format: 'number' },
+ { key: 'downloads', label: 'Downloads', format: 'number' },
+ { key: 'lastModified', label: 'Last Modified', format: 'datetime' },
+ gatedField,
+ { key: 'private', label: 'Private', format: 'boolean' },
+];
+
+const repoCardFields: OutputSchemaField[] = [
+ ...repoCardBaseFields,
+ { key: 'pipeline_tag', label: 'Pipeline Task', description: 'Models only.' },
+ { key: 'numParameters', label: 'Parameters', format: 'number', description: 'Models only.' },
+];
+
+const repoDetailCoreFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Repo ID' },
+ { key: 'author', label: 'Author' },
+ { key: 'tags', label: 'Tags' },
+ { key: 'likes', label: 'Likes', format: 'number' },
+ { key: 'sha', label: 'Latest Commit SHA' },
+ { key: 'lastModified', label: 'Last Modified', format: 'datetime' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'private', label: 'Private', format: 'boolean' },
+ gatedField,
+ { key: 'disabled', label: 'Disabled', format: 'boolean' },
+ { key: 'usedStorage', label: 'Used Storage', format: 'filesize' },
+];
+
+const siblingsField: OutputSchemaField = {
+ key: 'siblings',
+ label: 'Files',
+ labelKey: 'rfilename',
+ listItems: [{ key: 'rfilename', label: 'File Path' }],
+};
+
+const gitRefItemFields: OutputSchemaField[] = [
+ { key: 'name', label: 'Name' },
+ { key: 'ref', label: 'Ref' },
+ { key: 'targetCommit', label: 'Target Commit' },
+];
+
+const discussionSummaryFields: OutputSchemaField[] = [
+ { key: 'num', label: 'Number', format: 'number' },
+ { key: 'title', label: 'Title' },
+ { key: 'status', label: 'Status' },
+ { key: 'isPullRequest', label: 'Is Pull Request', format: 'boolean' },
+ { key: 'pinned', label: 'Pinned', format: 'boolean' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'author', label: 'Author', children: hubAccountFields },
+ {
+ key: 'repo',
+ label: 'Repo',
+ children: [
+ { key: 'name', label: 'Repo ID' },
+ { key: 'type', label: 'Repo Type' },
+ ],
+ },
+];
+
+const commentEventFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Event ID' },
+ { key: 'type', label: 'Event Type' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'author', label: 'Author', children: hubAccountFields },
+ {
+ key: 'data',
+ label: 'Data',
+ description: "For 'comment' events: the latest comment text and edit state.",
+ children: [
+ {
+ key: 'latest',
+ label: 'Latest Version',
+ children: [
+ { key: 'raw', label: 'Text (Markdown)' },
+ { key: 'html', label: 'Text (HTML)', format: 'html' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+ ],
+ },
+ { key: 'edited', label: 'Edited', format: 'boolean' },
+ { key: 'hidden', label: 'Hidden', format: 'boolean' },
+ { key: 'numEdits', label: 'Edit Count', format: 'number' },
+ ],
+ },
+];
+
+const paperAuthorsField: OutputSchemaField = {
+ key: 'authors',
+ label: 'Authors',
+ labelKey: 'name',
+ listItems: [{ key: 'name', label: 'Name' }],
+};
+
+const paperCoreFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Paper ID', description: 'The arXiv ID, for example 2307.09288.' },
+ { key: 'title', label: 'Title' },
+ { key: 'summary', label: 'Abstract' },
+ { key: 'publishedAt', label: 'Published At', format: 'datetime' },
+ { key: 'upvotes', label: 'Upvotes', format: 'number' },
+ paperAuthorsField,
+ { key: 'discussionId', label: 'Discussion ID' },
+];
+
+const paperListingFields: OutputSchemaField[] = [
+ { key: 'title', label: 'Title' },
+ { key: 'publishedAt', label: 'Published At', format: 'datetime' },
+ { key: 'thumbnail', label: 'Thumbnail', format: 'image' },
+ { key: 'numComments', label: 'Comments', format: 'number' },
+];
+
+const collectionFields: OutputSchemaField[] = [
+ { key: 'slug', label: 'Collection Slug' },
+ { key: 'title', label: 'Title' },
+ { key: 'description', label: 'Description' },
+ { key: 'lastUpdated', label: 'Last Updated', format: 'datetime' },
+ { key: 'private', label: 'Private', format: 'boolean' },
+ { key: 'upvotes', label: 'Upvotes', format: 'number' },
+ { key: 'owner', label: 'Owner', children: hubAccountFields },
+ {
+ key: 'items',
+ label: 'Items',
+ labelKey: 'id',
+ listItems: [
+ { key: 'type', label: 'Item Type' },
+ { key: 'position', label: 'Position', format: 'number' },
+ ...repoCardFields,
+ ],
+ },
+];
+
export const languageTranslationOutputSchema: OutputSchema = {
fields: [
{ key: 'translatedText', label: 'Translated Text' },
@@ -410,3 +579,583 @@ export const imageClassificationOutputSchema: OutputSchema = {
rawResultField('rawResults'),
],
};
+
+export const searchModelsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'models',
+ label: 'Models',
+ labelKey: 'id',
+ listItems: [
+ ...repoSearchCoreFields,
+ { key: 'pipeline_tag', label: 'Pipeline Task' },
+ { key: 'library_name', label: 'Library' },
+ { key: 'downloads', label: 'Downloads', format: 'number' },
+ ],
+ },
+ countField,
+ nextCursorField,
+ ],
+};
+
+export const searchDatasetsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'datasets',
+ label: 'Datasets',
+ labelKey: 'id',
+ listItems: [
+ ...repoSearchCoreFields,
+ { key: 'author', label: 'Author' },
+ { key: 'description', label: 'Description' },
+ { key: 'downloads', label: 'Downloads', format: 'number' },
+ { key: 'lastModified', label: 'Last Modified', format: 'datetime' },
+ gatedField,
+ { key: 'disabled', label: 'Disabled', format: 'boolean' },
+ { key: 'sha', label: 'Latest Commit SHA' },
+ ],
+ },
+ countField,
+ nextCursorField,
+ ],
+};
+
+export const searchSpacesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'spaces',
+ label: 'Spaces',
+ labelKey: 'id',
+ listItems: [...repoSearchCoreFields, { key: 'sdk', label: 'SDK' }],
+ },
+ countField,
+ nextCursorField,
+ ],
+};
+
+export const searchPapersOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'papers',
+ label: 'Papers',
+ labelKey: 'title',
+ listItems: [
+ ...paperListingFields,
+ {
+ key: 'paper',
+ label: 'Paper',
+ children: [
+ ...paperCoreFields,
+ { key: 'ai_summary', label: 'AI Summary' },
+ { key: 'ai_keywords', label: 'AI Keywords' },
+ ],
+ },
+ ],
+ },
+ countField,
+ ],
+};
+
+export const getModelOutputSchema: OutputSchema = {
+ fields: [
+ ...repoDetailCoreFields,
+ { key: 'pipeline_tag', label: 'Pipeline Task' },
+ { key: 'library_name', label: 'Library' },
+ { key: 'downloads', label: 'Downloads (Last 30 Days)', format: 'number' },
+ {
+ key: 'cardData',
+ label: 'Model Card Metadata',
+ children: [
+ { key: 'license', label: 'License' },
+ { key: 'language', label: 'Language' },
+ ],
+ },
+ {
+ key: 'safetensors',
+ label: 'Safetensors',
+ children: [{ key: 'total', label: 'Total Parameters', format: 'number' }],
+ },
+ siblingsField,
+ { key: 'spaces', label: 'Spaces Using This Model' },
+ ],
+};
+
+export const getDatasetOutputSchema: OutputSchema = {
+ fields: [
+ ...repoDetailCoreFields,
+ { key: 'description', label: 'Description' },
+ { key: 'downloads', label: 'Downloads (Last 30 Days)', format: 'number' },
+ { key: 'paperswithcode_id', label: 'Papers with Code ID' },
+ {
+ key: 'cardData',
+ label: 'Dataset Card Metadata',
+ children: [
+ { key: 'pretty_name', label: 'Pretty Name' },
+ { key: 'license', label: 'License' },
+ { key: 'language', label: 'Language' },
+ { key: 'task_categories', label: 'Task Categories' },
+ { key: 'size_categories', label: 'Size Categories' },
+ ],
+ },
+ siblingsField,
+ ],
+};
+
+export const getSpaceOutputSchema: OutputSchema = {
+ fields: [
+ ...repoDetailCoreFields,
+ { key: 'sdk', label: 'SDK' },
+ { key: 'host', label: 'App URL', format: 'url' },
+ { key: 'subdomain', label: 'Subdomain' },
+ { key: 'region', label: 'Region' },
+ {
+ key: 'cardData',
+ label: 'Space Card Metadata',
+ children: [
+ { key: 'title', label: 'Title' },
+ { key: 'emoji', label: 'Emoji' },
+ { key: 'sdk_version', label: 'SDK Version' },
+ { key: 'app_file', label: 'App File' },
+ ],
+ },
+ {
+ key: 'runtime',
+ label: 'Runtime',
+ children: [
+ { key: 'stage', label: 'Stage' },
+ {
+ key: 'hardware',
+ label: 'Hardware',
+ children: [
+ { key: 'current', label: 'Current' },
+ { key: 'requested', label: 'Requested' },
+ ],
+ },
+ ],
+ },
+ siblingsField,
+ ],
+};
+
+export const listTrendingReposOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'repos',
+ label: 'Trending Repos',
+ labelKey: 'id',
+ listItems: [
+ { key: 'repo_type', label: 'Repo Type' },
+ ...repoCardFields,
+ { key: 'title', label: 'Title', description: 'Spaces only.' },
+ { key: 'emoji', label: 'Emoji', description: 'Spaces only.' },
+ { key: 'shortDescription', label: 'Short Description', description: 'Spaces only.' },
+ { key: 'ai_short_description', label: 'AI Short Description', description: 'Spaces only.' },
+ { key: 'ai_category', label: 'AI Category', description: 'Spaces only.' },
+ {
+ key: 'runtime',
+ label: 'Runtime',
+ description: 'Spaces only.',
+ children: [{ key: 'stage', label: 'Stage' }],
+ },
+ ],
+ },
+ countField,
+ ],
+};
+
+export const listHubTagsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'tags_by_type',
+ label: 'Tags by Type',
+ value: '',
+ dynamicKey: true,
+ description:
+ "One entry per tag type (for example 'library' or 'pipeline_tag'), each a list of {id, label, type} tags. Use a tag's id as a Tag Filters value.",
+ },
+ ],
+};
+
+export const listRepoFilesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'files',
+ label: 'Files',
+ labelKey: 'path',
+ listItems: [
+ { key: 'path', label: 'Path' },
+ { key: 'type', label: 'Type', description: "'file' or 'directory'." },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'oid', label: 'Git Object ID' },
+ {
+ key: 'lfs',
+ label: 'LFS',
+ description: 'Only present for files stored with Git LFS.',
+ children: [
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'oid', label: 'SHA-256' },
+ ],
+ },
+ ],
+ },
+ countField,
+ nextCursorField,
+ ],
+};
+
+export const getRepoPathsInfoOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'paths',
+ label: 'Paths',
+ labelKey: 'path',
+ listItems: [
+ { key: 'path', label: 'Path' },
+ { key: 'type', label: 'Type', description: "'file' or 'directory'." },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'oid', label: 'Git Object ID' },
+ {
+ key: 'lastCommit',
+ label: 'Last Commit',
+ children: [
+ { key: 'id', label: 'Commit SHA' },
+ { key: 'title', label: 'Title' },
+ { key: 'date', label: 'Date', format: 'datetime' },
+ ],
+ },
+ {
+ key: 'securityFileStatus',
+ label: 'Security Status',
+ children: [{ key: 'status', label: 'Overall Status' }],
+ },
+ ],
+ },
+ countField,
+ ],
+};
+
+export const readRepoFileOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'content', label: 'Content' },
+ { key: 'path', label: 'Path' },
+ { key: 'size_bytes', label: 'Size', format: 'filesize' },
+ { key: 'url', label: 'Download URL', format: 'url' },
+ { key: 'repo_id', label: 'Repo ID' },
+ { key: 'repo_type', label: 'Repo Type' },
+ { key: 'revision', label: 'Revision' },
+ ],
+};
+
+export const listRepoCommitsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'commits',
+ label: 'Commits',
+ labelKey: 'title',
+ listItems: [
+ { key: 'id', label: 'Commit SHA' },
+ { key: 'title', label: 'Title' },
+ { key: 'message', label: 'Message' },
+ { key: 'date', label: 'Date', format: 'datetime' },
+ {
+ key: 'authors',
+ label: 'Authors',
+ labelKey: 'user',
+ listItems: [
+ { key: 'user', label: 'Username' },
+ { key: 'avatar', label: 'Avatar', format: 'image' },
+ ],
+ },
+ ],
+ },
+ countField,
+ pageField,
+ nextPageField,
+ ],
+};
+
+export const listRepoRefsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'branches', label: 'Branches', labelKey: 'name', listItems: gitRefItemFields },
+ { key: 'tags', label: 'Tags', labelKey: 'name', listItems: gitRefItemFields },
+ { key: 'converts', label: 'Converts', labelKey: 'name', listItems: gitRefItemFields },
+ { key: 'pullRequests', label: 'Pull Requests', labelKey: 'name', listItems: gitRefItemFields },
+ ],
+};
+
+export const compareRepoRevisionsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'diff', label: 'Diff' },
+ { key: 'base', label: 'Base Revision' },
+ { key: 'head', label: 'Head Revision' },
+ { key: 'truncated', label: 'Truncated', format: 'boolean' },
+ { key: 'diff_length', label: 'Diff Length', format: 'number' },
+ ],
+};
+
+export const getRepoSizeOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'path', label: 'Path' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ ],
+};
+
+export const getRepoSecurityScanOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'scansDone', label: 'Scans Done', format: 'boolean' },
+ { key: 'filesWithIssues', label: 'Files With Issues' },
+ ],
+};
+
+export const getCurrentUserOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'username', label: 'Username' },
+ { key: 'full_name', label: 'Full Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'email_verified', label: 'Email Verified', format: 'boolean' },
+ { key: 'is_pro', label: 'Is Pro', format: 'boolean' },
+ { key: 'avatar_url', label: 'Avatar URL' },
+ { key: 'account_type', label: 'Account Type' },
+ {
+ key: 'organizations',
+ label: 'Organizations',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'full_name', label: 'Full Name' },
+ { key: 'role_in_org', label: 'Role' },
+ { key: 'is_enterprise', label: 'Is Enterprise', format: 'boolean' },
+ ],
+ },
+ { key: 'token_name', label: 'Token Name' },
+ { key: 'token_created_at', label: 'Token Created At', format: 'datetime' },
+ { key: 'token_role', label: 'Token Role' },
+ { key: 'token_can_read_gated_repos', label: 'Token Can Read Gated Repos', format: 'boolean' },
+ { key: 'token_global_permissions', label: 'Token Global Permissions' },
+ {
+ key: 'token_scoped_permissions',
+ label: 'Token Scoped Permissions',
+ labelKey: 'entity_name',
+ listItems: [
+ { key: 'entity_type', label: 'Entity Type' },
+ { key: 'entity_name', label: 'Entity Name' },
+ { key: 'permissions', label: 'Permissions' },
+ ],
+ },
+ ],
+};
+
+export const getUserOverviewOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'user', label: 'Username' },
+ { key: 'fullname', label: 'Full Name' },
+ { key: 'type', label: 'Account Type' },
+ { key: 'details', label: 'Bio' },
+ { key: 'avatarUrl', label: 'Avatar', format: 'image' },
+ { key: 'isPro', label: 'Is Pro', format: 'boolean' },
+ { key: 'createdAt', label: 'Joined At', format: 'datetime' },
+ { key: 'numModels', label: 'Models', format: 'number' },
+ { key: 'numDatasets', label: 'Datasets', format: 'number' },
+ { key: 'numSpaces', label: 'Spaces', format: 'number' },
+ { key: 'numPapers', label: 'Papers', format: 'number' },
+ { key: 'numDiscussions', label: 'Discussions', format: 'number' },
+ { key: 'numUpvotes', label: 'Upvotes', format: 'number' },
+ { key: 'numLikes', label: 'Likes', format: 'number' },
+ { key: 'numFollowers', label: 'Followers', format: 'number' },
+ { key: 'numFollowing', label: 'Following', format: 'number' },
+ {
+ key: 'orgs',
+ label: 'Organizations',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'fullname', label: 'Full Name' },
+ ],
+ },
+ ],
+};
+
+export const getOrganizationOverviewOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'name', label: 'Name' },
+ { key: 'fullname', label: 'Full Name' },
+ { key: 'details', label: 'Description' },
+ { key: 'avatarUrl', label: 'Avatar', format: 'image' },
+ { key: 'isVerified', label: 'Verified', format: 'boolean' },
+ { key: 'plan', label: 'Plan' },
+ { key: 'numUsers', label: 'Members', format: 'number' },
+ { key: 'numModels', label: 'Models', format: 'number' },
+ { key: 'numDatasets', label: 'Datasets', format: 'number' },
+ { key: 'numSpaces', label: 'Spaces', format: 'number' },
+ { key: 'numPapers', label: 'Papers', format: 'number' },
+ { key: 'numFollowers', label: 'Followers', format: 'number' },
+ ],
+};
+
+export const listOrganizationMembersOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'members',
+ label: 'Members',
+ labelKey: 'user',
+ listItems: [
+ { key: 'user', label: 'Username' },
+ { key: 'fullname', label: 'Full Name' },
+ { key: 'type', label: 'Account Type' },
+ { key: 'isPro', label: 'Is Pro', format: 'boolean' },
+ ],
+ },
+ countField,
+ nextCursorField,
+ ],
+};
+
+export const listDiscussionsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'discussions',
+ label: 'Discussions',
+ labelKey: 'title',
+ listItems: [...discussionSummaryFields, { key: 'numComments', label: 'Comments', format: 'number' }],
+ },
+ countField,
+ { key: 'total_count', label: 'Total Count', format: 'number' },
+ pageField,
+ nextPageField,
+ ],
+};
+
+export const getDiscussionOutputSchema: OutputSchema = {
+ fields: [
+ ...discussionSummaryFields,
+ { key: 'locked', label: 'Locked', format: 'boolean' },
+ { key: 'events', label: 'Events', labelKey: 'type', listItems: commentEventFields },
+ ],
+};
+
+export const listDailyPapersOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'papers',
+ label: 'Papers',
+ labelKey: 'title',
+ listItems: [
+ ...paperListingFields,
+ {
+ key: 'paper',
+ label: 'Paper',
+ children: [
+ ...paperCoreFields,
+ { key: 'submittedOnDailyAt', label: 'Submitted to Daily Papers At', format: 'datetime' },
+ ],
+ },
+ { key: 'submittedBy', label: 'Submitted By', children: hubAccountFields },
+ ],
+ },
+ countField,
+ pageField,
+ nextPageField,
+ ],
+};
+
+export const getPaperOutputSchema: OutputSchema = {
+ fields: [
+ ...paperCoreFields,
+ { key: 'ai_summary', label: 'AI Summary' },
+ { key: 'ai_keywords', label: 'AI Keywords' },
+ { key: 'submittedOnDailyAt', label: 'Submitted to Daily Papers At', format: 'datetime' },
+ {
+ key: 'submittedOnDailyBy',
+ label: 'Submitted By',
+ children: [
+ { key: 'user', label: 'Username' },
+ { key: 'fullname', label: 'Full Name' },
+ ],
+ },
+ { key: 'githubRepo', label: 'GitHub Repo', format: 'url' },
+ { key: 'githubStars', label: 'GitHub Stars', format: 'number' },
+ { key: 'linkedModels', label: 'Linked Models', labelKey: 'id', listItems: repoCardFields },
+ { key: 'numTotalModels', label: 'Total Linked Models', format: 'number' },
+ { key: 'linkedDatasets', label: 'Linked Datasets', labelKey: 'id', listItems: repoCardBaseFields },
+ { key: 'numTotalDatasets', label: 'Total Linked Datasets', format: 'number' },
+ {
+ key: 'linkedSpaces',
+ label: 'Linked Spaces',
+ labelKey: 'id',
+ listItems: [
+ { key: 'id', label: 'Space ID' },
+ { key: 'emoji', label: 'Emoji' },
+ { key: 'shortDescription', label: 'Short Description' },
+ { key: 'running', label: 'Running', format: 'boolean' },
+ ],
+ },
+ { key: 'numTotalSpaces', label: 'Total Linked Spaces', format: 'number' },
+ {
+ key: 'comments',
+ label: 'Comments',
+ labelKey: 'id',
+ description: 'Only present when Include Comments is on.',
+ listItems: [
+ ...commentEventFields,
+ { key: 'replies', label: 'Replies', labelKey: 'id', listItems: commentEventFields },
+ ],
+ },
+ ],
+};
+
+export const listCollectionsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'collections', label: 'Collections', labelKey: 'title', listItems: collectionFields },
+ countField,
+ nextCursorField,
+ ],
+};
+
+export const getCollectionOutputSchema: OutputSchema = {
+ fields: [...collectionFields, { key: 'shareUrl', label: 'Share URL', format: 'url' }],
+};
+
+export const generateChatCompletionOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'content',
+ label: 'Reply',
+ description: "Empty with finish_reason 'length' means Max Tokens ran out, often on hidden reasoning.",
+ },
+ { key: 'finish_reason', label: 'Finish Reason' },
+ { key: 'model', label: 'Model' },
+ { key: 'id', label: 'Completion ID' },
+ {
+ key: 'usage',
+ label: 'Token Usage',
+ children: [
+ { key: 'prompt_tokens', label: 'Prompt Tokens', format: 'number' },
+ { key: 'completion_tokens', label: 'Completion Tokens', format: 'number' },
+ { key: 'total_tokens', label: 'Total Tokens', format: 'number' },
+ ],
+ },
+ ],
+};
+
+export const generateEmbeddingsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'model', label: 'Model' },
+ { key: 'dimensions', label: 'Dimensions', format: 'number' },
+ {
+ key: 'embedding',
+ label: 'Embedding',
+ description: 'The vector for a single input text. Only present when one text was sent.',
+ },
+ {
+ key: 'embeddings',
+ label: 'Embeddings',
+ description: 'One vector per input text, in input order. Only present when several texts were sent.',
+ },
+ {
+ key: 'count',
+ label: 'Count',
+ format: 'number',
+ description: 'Number of vectors returned. Only present when several texts were sent.',
+ },
+ ],
+};
diff --git a/packages/pieces/community/hugging-face/test/helpers.ts b/packages/pieces/community/hugging-face/test/helpers.ts
new file mode 100644
index 00000000000..a2132688316
--- /dev/null
+++ b/packages/pieces/community/hugging-face/test/helpers.ts
@@ -0,0 +1,31 @@
+import { Readable } from 'node:stream';
+import {
+ ActionContext,
+ AppConnectionType,
+ InputPropertyMap,
+ SecretTextProperty,
+ StaticPropsValue,
+} from '@activepieces/pieces-framework';
+import { createMockActionContext } from '../../../framework/src/lib/test';
+
+export function runAction<Props extends InputPropertyMap>({ action, propsValue }: RunActionParams<Props>) {
+ const context: ActionContext<SecretTextProperty<true>, Props> = {
+ ...createMockActionContext<Props>({ propsValue }),
+ auth: { type: AppConnectionType.SECRET_TEXT, secret_text: TEST_TOKEN },
+ };
+ return action.run(context);
+}
+
+export function streamOf(content: string | Buffer): Readable {
+ return Readable.from([typeof content === 'string' ? Buffer.from(content) : content]);
+}
+
+export const TEST_TOKEN = 'hf_test_connection_token';
+
+type RunActionParams<Props extends InputPropertyMap> = {
+ action: {
+ props: Props;
+ run: (context: ActionContext<SecretTextProperty<true>, Props>) => Promise<unknown>;
+ };
+ propsValue: StaticPropsValue<Props>;
+};
diff --git a/packages/pieces/community/hugging-face/test/hub.test.ts b/packages/pieces/community/hugging-face/test/hub.test.ts
new file mode 100644
index 00000000000..0b0f757e027
--- /dev/null
+++ b/packages/pieces/community/hugging-face/test/hub.test.ts
@@ -0,0 +1,280 @@
+import { AuthenticationType, HttpMethod } from '@activepieces/pieces-common';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { getCurrentUser } from '../src/lib/actions/get-current-user';
+import { readRepoFile } from '../src/lib/actions/read-repo-file';
+import { searchModels } from '../src/lib/actions/search-models';
+import { hfHub } from '../src/lib/common/hub-client';
+import { hfRepo } from '../src/lib/common/repo';
+import { StaticPropsValue } from '@activepieces/pieces-framework';
+import { runAction, streamOf, TEST_TOKEN } from './helpers';
+
+const sendRequest = vi.fn();
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return {
+ ...actual,
+ httpClient: {
+ sendRequest: (...args: unknown[]) => sendRequest(...args),
+ },
+ };
+});
+
+function readFile(overrides: Partial<StaticPropsValue<typeof readRepoFile.props>>) {
+ return runAction({
+ action: readRepoFile,
+ propsValue: {
+ repo_type: 'model',
+ repo_id: 'openai-community/gpt2',
+ path: 'README.md',
+ revision: undefined,
+ ...overrides,
+ },
+ });
+}
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('Link header pagination', () => {
+ it('extracts the next cursor from a rel="next" Link header', () => {
+ const headers = {
+ link: '<https://huggingface.co/api/models?limit=2&cursor=eyJwYWdlIjoyfQ%3D%3D>; rel="next"',
+ };
+
+ expect(hfHub.parseNextCursor(headers)).toBe('eyJwYWdlIjoyfQ==');
+ });
+
+ it('returns null when there is no next link', () => {
+ expect(hfHub.parseNextCursor({})).toBeNull();
+ expect(hfHub.parseNextCursor(undefined)).toBeNull();
+ expect(hfHub.parseNextCursor({ link: '<https://huggingface.co/api/models?cursor=abc>; rel="prev"' })).toBeNull();
+ });
+
+ it('reads other query params from the next link', () => {
+ const headers = { link: '<https://huggingface.co/api/models/a/b/commits/main?p=3>; rel="next"' };
+
+ expect(hfHub.parseNextLinkParam({ headers, param: 'p' })).toBe('3');
+ });
+
+ it('surfaces next_cursor on a search action and forwards the cursor', async () => {
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: { link: '<https://huggingface.co/api/models?cursor=next123>; rel="next"' },
+ body: [{ id: 'openai/gpt-oss-20b' }],
+ });
+
+ const result = await runAction({
+ action: searchModels,
+ propsValue: {
+ search: 'gpt',
+ author: undefined,
+ filter: undefined,
+ pipeline_tag: undefined,
+ inference_provider: undefined,
+ sort: undefined,
+ limit: 1,
+ full: undefined,
+ cursor: 'prev456',
+ },
+ });
+
+ expect(result).toMatchObject({ next_cursor: 'next123' });
+ const url = new URL(sendRequest.mock.calls[0][0].url);
+ expect(url.searchParams.get('cursor')).toBe('prev456');
+ });
+});
+
+describe('repository id and revision encoding', () => {
+ it('encodes each id segment separately and keeps the slash', () => {
+ expect(hfRepo.encodeRepoId('my org/my model')).toBe('my%20org/my%20model');
+ expect(hfRepo.encodeRepoId('/openai-community/gpt2/')).toBe('openai-community/gpt2');
+ });
+
+ it('rejects ids with more than two segments', () => {
+ expect(() => hfRepo.encodeRepoId('a/b/c')).toThrow(/Invalid repository ID/);
+ });
+
+ it('encodes a PR ref as one path segment and defaults to main', () => {
+ expect(hfRepo.encodeRevision('refs/pr/1')).toBe('refs%2Fpr%2F1');
+ expect(hfRepo.encodeRevision(undefined)).toBe('main');
+ expect(hfRepo.encodeRevision(' ')).toBe('main');
+ });
+
+ it('encodes file path segments but keeps folder separators', () => {
+ expect(hfRepo.encodeFilePath('configs/my file#1.json')).toBe('configs/my%20file%231.json');
+ });
+
+ it('resolves a legacy single-segment id through the Hub API', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: { id: 'openai-community/gpt2' } });
+
+ const canonical = await hfRepo.resolveRepoId({ token: TEST_TOKEN, repoType: 'model', repoId: 'gpt2' });
+
+ expect(canonical).toBe('openai-community/gpt2');
+ expect(sendRequest.mock.calls[0][0].url).toBe('https://huggingface.co/api/models/gpt2');
+ });
+});
+
+describe('read_repo_file', () => {
+ it('builds the resolve URL with encoded id, revision and path', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: streamOf('# Hi') });
+
+ const result = await readFile({
+ repo_type: 'dataset',
+ repo_id: 'my org/data',
+ revision: 'refs/pr/1',
+ path: 'docs/read me.md',
+ });
+
+ const expectedUrl = 'https://huggingface.co/datasets/my%20org/data/resolve/refs%2Fpr%2F1/docs/read%20me.md';
+ expect(sendRequest.mock.calls[0][0]).toMatchObject({
+ method: HttpMethod.GET,
+ url: expectedUrl,
+ followRedirects: false,
+ responseType: 'stream',
+ authentication: { type: AuthenticationType.BEARER_TOKEN, token: TEST_TOKEN },
+ });
+ expect(result).toEqual({
+ repo_type: 'dataset',
+ repo_id: 'my org/data',
+ revision: 'refs/pr/1',
+ path: 'docs/read me.md',
+ content: '# Hi',
+ size_bytes: 4,
+ url: expectedUrl,
+ });
+ });
+
+ it('keeps Authorization on a same-host redirect and drops it on a cross-host redirect', async () => {
+ sendRequest
+ .mockResolvedValueOnce({
+ status: 307,
+ headers: { location: '/api/resolve-cache/models/openai-community/gpt2/abc/README.md' },
+ body: streamOf(''),
+ })
+ .mockResolvedValueOnce({
+ status: 302,
+ headers: { location: 'https://cas-bridge.xethub.hf.co/xet-bridge/abc?X-Amz-Signature=sig' },
+ body: streamOf(''),
+ })
+ .mockResolvedValueOnce({ status: 200, headers: {}, body: streamOf('hello') });
+
+ const result = await readFile({});
+
+ expect(sendRequest).toHaveBeenCalledTimes(3);
+ const [first, second, third] = sendRequest.mock.calls.map((call) => call[0]);
+ expect(first.authentication).toEqual({ type: AuthenticationType.BEARER_TOKEN, token: TEST_TOKEN });
+ expect(second.url).toBe('https://huggingface.co/api/resolve-cache/models/openai-community/gpt2/abc/README.md');
+ expect(second.authentication).toEqual({ type: AuthenticationType.BEARER_TOKEN, token: TEST_TOKEN });
+ expect(third.url).toBe('https://cas-bridge.xethub.hf.co/xet-bridge/abc?X-Amz-Signature=sig');
+ expect(third.authentication).toBeUndefined();
+ expect(JSON.stringify(third)).not.toContain(TEST_TOKEN);
+ expect(result).toMatchObject({ content: 'hello', size_bytes: 5 });
+ });
+
+ it('fails with FILE_TOO_LARGE from the redirect x-linked-size before following it', async () => {
+ sendRequest.mockResolvedValueOnce({
+ status: 302,
+ headers: { location: 'https://cdn-lfs.hf.co/file', 'x-linked-size': String(5 * 1024 * 1024) },
+ body: streamOf(''),
+ });
+
+ await expect(readFile({ path: 'model.safetensors' })).rejects.toThrow(/^FILE_TOO_LARGE: the file is 5242880 bytes/);
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('fails with FILE_TOO_LARGE from content-length', async () => {
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: { 'content-length': String(hfHub.maxTextFileBytes + 1) },
+ body: streamOf('x'),
+ });
+
+ await expect(readFile({})).rejects.toThrow(/^FILE_TOO_LARGE/);
+ });
+
+ it('fails with FILE_TOO_LARGE when an unsized stream exceeds the cap', async () => {
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: {},
+ body: streamOf(Buffer.alloc(hfHub.maxTextFileBytes + 1, 97)),
+ });
+
+ await expect(readFile({})).rejects.toThrow(/^FILE_TOO_LARGE: the file is more than/);
+ });
+
+ it('fails with BINARY_FILE for content with NUL bytes', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: streamOf(Buffer.from([0x50, 0x4b, 0x00, 0x03])) });
+
+ await expect(readFile({ path: 'weights.bin' })).rejects.toThrow(/^BINARY_FILE/);
+ });
+
+ it('fails with BINARY_FILE for invalid UTF-8', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: streamOf(Buffer.from([0xff, 0xfe, 0x41])) });
+
+ await expect(readFile({})).rejects.toThrow(/^BINARY_FILE/);
+ });
+
+ it('stops after too many redirects', async () => {
+ sendRequest.mockImplementation(async () => ({
+ status: 302,
+ headers: { location: 'https://huggingface.co/loop' },
+ body: streamOf(''),
+ }));
+
+ await expect(readFile({})).rejects.toThrow(/Too many redirects/);
+ });
+
+ it('rejects an empty file path without a request', async () => {
+ await expect(readFile({ path: '//' })).rejects.toThrow(/File Path is required/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('get_current_user', () => {
+ it('returns token metadata but never token material', async () => {
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: {},
+ body: {
+ name: 'odai',
+ fullname: 'Odai',
+ type: 'user',
+ orgs: [{ name: 'acme', fullname: 'Acme', roleInOrg: 'admin', isEnterprise: false }],
+ auth: {
+ type: 'access_token',
+ accessToken: {
+ displayName: 'automation',
+ role: 'fineGrained',
+ createdAt: '2026-01-02T03:04:05.000Z',
+ token: 'hf_leaked_value_from_api',
+ fineGrained: {
+ canReadGatedRepos: true,
+ global: ['inference.serverless.write'],
+ scoped: [{ entity: { type: 'user', name: 'odai' }, permissions: ['repo.content.read'] }],
+ },
+ },
+ },
+ },
+ });
+
+ const result = await runAction({ action: getCurrentUser, propsValue: {} });
+
+ expect(sendRequest.mock.calls[0][0].url).toBe('https://huggingface.co/api/whoami-v2');
+ expect(result).toMatchObject({
+ username: 'odai',
+ token_name: 'automation',
+ token_role: 'fineGrained',
+ token_created_at: '2026-01-02T03:04:05.000Z',
+ token_can_read_gated_repos: true,
+ token_global_permissions: ['inference.serverless.write'],
+ organizations: [{ name: 'acme', role_in_org: 'admin' }],
+ });
+ const serialized = JSON.stringify(result);
+ expect(serialized).not.toContain('hf_leaked_value_from_api');
+ expect(serialized).not.toContain(TEST_TOKEN);
+ expect(result).not.toHaveProperty('token');
+ expect(result).not.toHaveProperty('access_token');
+ });
+});
diff --git a/packages/pieces/community/hugging-face/test/inference.test.ts b/packages/pieces/community/hugging-face/test/inference.test.ts
new file mode 100644
index 00000000000..c135d7e5e02
--- /dev/null
+++ b/packages/pieces/community/hugging-face/test/inference.test.ts
@@ -0,0 +1,252 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { generateEmbeddings } from '../src/lib/actions/generate-embeddings';
+import { generateChatCompletion } from '../src/lib/actions/generate-chat-completion';
+import { hfInference } from '../src/lib/common/inference';
+import { StaticPropsValue } from '@activepieces/pieces-framework';
+import { runAction, TEST_TOKEN } from './helpers';
+
+const featureExtraction = vi.fn();
+const chatCompletion = vi.fn();
+const clientTokens: string[] = [];
+
+vi.mock('@huggingface/inference', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@huggingface/inference')>();
+ return {
+ ...actual,
+ InferenceClient: class {
+ constructor(token: string) {
+ clientTokens.push(token);
+ }
+ featureExtraction = (...args: unknown[]) => featureExtraction(...args);
+ chatCompletion = (...args: unknown[]) => chatCompletion(...args);
+ },
+ };
+});
+
+function runEmbeddings(overrides: Partial<StaticPropsValue<typeof generateEmbeddings.props>>) {
+ return runAction({
+ action: generateEmbeddings,
+ propsValue: {
+ model: 'BAAI/bge-small-en-v1.5',
+ provider: undefined,
+ inputs: [],
+ normalize: undefined,
+ truncate: undefined,
+ truncation_direction: undefined,
+ prompt_name: undefined,
+ ...overrides,
+ },
+ });
+}
+
+function runChat(overrides: Partial<StaticPropsValue<typeof generateChatCompletion.props>>) {
+ return runAction({
+ action: generateChatCompletion,
+ propsValue: {
+ model: undefined,
+ provider: undefined,
+ messages: JSON.parse('[{"role": "user", "content": "Hi"}]'),
+ system_prompt: undefined,
+ max_tokens: undefined,
+ temperature: undefined,
+ top_p: undefined,
+ stop: undefined,
+ seed: undefined,
+ response_format: undefined,
+ json_schema: undefined,
+ ...overrides,
+ },
+ });
+}
+
+beforeEach(() => {
+ featureExtraction.mockReset();
+ chatCompletion.mockReset();
+ clientTokens.length = 0;
+});
+
+describe('generate_embeddings shape handling', () => {
+ it('returns a flat vector for one text as the embedding', async () => {
+ featureExtraction.mockResolvedValueOnce([0.1, 0.2, 0.3]);
+
+ const result = await runEmbeddings({ inputs: ['hello'] });
+
+ expect(result).toEqual({ model: 'BAAI/bge-small-en-v1.5', embedding: [0.1, 0.2, 0.3], dimensions: 3 });
+ expect(featureExtraction.mock.calls[0][0].inputs).toBe('hello');
+ expect(clientTokens).toEqual([TEST_TOKEN]);
+ });
+
+ it('unwraps a single pooled vector wrapped in an outer array', async () => {
+ featureExtraction.mockResolvedValueOnce([[0.5, 0.6]]);
+
+ const result = await runEmbeddings({ inputs: ['hello'] });
+
+ expect(result).toEqual({ model: 'BAAI/bge-small-en-v1.5', embedding: [0.5, 0.6], dimensions: 2 });
+ });
+
+ it('rejects token-level vectors for one text instead of returning the first token', async () => {
+ featureExtraction.mockResolvedValueOnce([
+ [0.1, 0.2],
+ [0.3, 0.4],
+ [0.5, 0.6],
+ ]);
+
+ await expect(runEmbeddings({ inputs: ['hello world'] })).rejects.toThrow(/token-level vectors/);
+ });
+
+ it('rejects token-level vectors for one text wrapped in a batch array', async () => {
+ featureExtraction.mockResolvedValueOnce([
+ [
+ [0.1, 0.2],
+ [0.3, 0.4],
+ ],
+ ]);
+
+ await expect(runEmbeddings({ inputs: ['hello world'] })).rejects.toThrow(/token-level vectors/);
+ });
+
+ it('returns one pooled vector per text, in order, for several texts', async () => {
+ featureExtraction.mockResolvedValueOnce([
+ [1, 2],
+ [3, 4],
+ ]);
+
+ const result = await runEmbeddings({ inputs: ['a', 'b'] });
+
+ expect(result).toEqual({
+ model: 'BAAI/bge-small-en-v1.5',
+ embeddings: [
+ [1, 2],
+ [3, 4],
+ ],
+ count: 2,
+ dimensions: 2,
+ });
+ expect(featureExtraction.mock.calls[0][0].inputs).toEqual(['a', 'b']);
+ });
+
+ it('rejects token-level vectors for several texts with the same typed error', async () => {
+ featureExtraction.mockResolvedValueOnce([
+ [
+ [1, 2],
+ [3, 4],
+ ],
+ [
+ [5, 6],
+ [7, 8],
+ ],
+ ]);
+
+ await expect(runEmbeddings({ inputs: ['a', 'b'] })).rejects.toThrow(/token-level vectors/);
+ });
+
+ it('rejects a result whose count does not match the number of texts', async () => {
+ featureExtraction.mockResolvedValueOnce([[1, 2]]);
+
+ await expect(runEmbeddings({ inputs: ['a', 'b'] })).rejects.toThrow(/one pooled embedding per text/);
+ });
+
+ it('rejects empty input before calling the provider', async () => {
+ await expect(runEmbeddings({ inputs: [' '] })).rejects.toThrow(/at least one non-empty text/);
+ expect(featureExtraction).not.toHaveBeenCalled();
+ });
+});
+
+describe('resolveModelAndProvider', () => {
+ it('falls back to the default model when the model is empty', () => {
+ expect(hfInference.resolveModelAndProvider({ model: ' ', provider: undefined, defaultModel: 'openai/gpt-oss-20b' })).toEqual({
+ model: 'openai/gpt-oss-20b',
+ provider: undefined,
+ });
+ });
+
+ it('keeps a model without a suffix and uses the selected provider', () => {
+ expect(hfInference.resolveModelAndProvider({ model: 'Qwen/Qwen3-8B', provider: 'groq' })).toEqual({
+ model: 'Qwen/Qwen3-8B',
+ provider: 'groq',
+ });
+ });
+
+ it('turns a :groq suffix into the provider', () => {
+ expect(hfInference.resolveModelAndProvider({ model: 'Qwen/Qwen3-8B:groq', provider: undefined })).toEqual({
+ model: 'Qwen/Qwen3-8B',
+ provider: 'groq',
+ });
+ });
+
+ it('maps :preferred to the auto policy', () => {
+ expect(hfInference.resolveModelAndProvider({ model: 'Qwen/Qwen3-8B:preferred', provider: undefined })).toEqual({
+ model: 'Qwen/Qwen3-8B',
+ provider: 'auto',
+ });
+ });
+
+ it('rejects the :fastest and :cheapest routing policies', () => {
+ expect(() => hfInference.resolveModelAndProvider({ model: 'Qwen/Qwen3-8B:fastest', provider: undefined })).toThrow(
+ /':fastest' routing policy is not supported/
+ );
+ expect(() => hfInference.resolveModelAndProvider({ model: 'Qwen/Qwen3-8B:cheapest', provider: undefined })).toThrow(
+ /':cheapest' routing policy is not supported/
+ );
+ });
+
+ it('rejects a suffix that conflicts with the selected provider', () => {
+ expect(() => hfInference.resolveModelAndProvider({ model: 'Qwen/Qwen3-8B:groq', provider: 'together' })).toThrow(
+ /conflicts with the selected provider 'together'/
+ );
+ });
+
+ it('accepts a suffix that matches the selected provider', () => {
+ expect(hfInference.resolveModelAndProvider({ model: 'Qwen/Qwen3-8B:groq', provider: 'groq' })).toEqual({
+ model: 'Qwen/Qwen3-8B',
+ provider: 'groq',
+ });
+ });
+
+ it('rejects unknown providers and suffixes', () => {
+ expect(() => hfInference.resolveModelAndProvider({ model: 'Qwen/Qwen3-8B', provider: 'nope' })).toThrow(
+ /Unknown inference provider 'nope'/
+ );
+ expect(() => hfInference.resolveModelAndProvider({ model: 'Qwen/Qwen3-8B:nope', provider: undefined })).toThrow(
+ /Unknown provider suffix ':nope'/
+ );
+ });
+});
+
+describe('generate_chat_completion model selection', () => {
+ it('uses openai/gpt-oss-20b when the model is left empty', async () => {
+ chatCompletion.mockResolvedValueOnce({ choices: [{ message: { content: 'Hello' }, finish_reason: 'stop' }] });
+
+ const result = await runChat({ model: undefined });
+
+ expect(chatCompletion.mock.calls[0][0]).toMatchObject({ model: 'openai/gpt-oss-20b', provider: undefined });
+ expect(result).toMatchObject({ content: 'Hello', finish_reason: 'stop', model: 'openai/gpt-oss-20b' });
+ });
+
+ it('accepts any typed model ID with a provider suffix', async () => {
+ chatCompletion.mockResolvedValueOnce({ model: 'meta-llama/Llama-3.1-8B-Instruct', choices: [] });
+
+ await runChat({ model: 'meta-llama/Llama-3.1-8B-Instruct:groq' });
+
+ expect(chatCompletion.mock.calls[0][0]).toMatchObject({
+ model: 'meta-llama/Llama-3.1-8B-Instruct',
+ provider: 'groq',
+ });
+ });
+
+ it('prepends the system prompt as a leading system message', async () => {
+ chatCompletion.mockResolvedValueOnce({ choices: [] });
+
+ await runChat({ model: 'openai/gpt-oss-20b', system_prompt: 'Be brief.' });
+
+ expect(chatCompletion.mock.calls[0][0].messages).toEqual([
+ { role: 'system', content: 'Be brief.' },
+ { role: 'user', content: 'Hi' },
+ ]);
+ });
+
+ it('rejects a routing policy suffix before calling the provider', async () => {
+ await expect(runChat({ model: 'openai/gpt-oss-20b:fastest' })).rejects.toThrow(/not supported/);
+ expect(chatCompletion).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pieces/community/hugging-face/vitest.config.ts b/packages/pieces/community/hugging-face/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/hugging-face/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})