### Install HuggingFace Gem Source: https://github.com/fwdai/hugging-face/blob/main/README.md Instructions for adding the hugging-face gem to a Ruby project using Bundler or direct installation via command line. ```shell $ bundle add hugging-face $ gem install hugging-face ``` -------------------------------- ### Install Hugging Face Ruby Gem Source: https://context7.com/fwdai/hugging-face/llms.txt Instructions on how to add the hugging-face gem to your Ruby project's Gemfile or install it directly, and how to require it in your application. ```ruby # Add to your Gemfile gem 'hugging-face' # Or install directly # $ gem install hugging-face # Require in your application require 'hugging_face' ``` -------------------------------- ### Perform Inference API Tasks Source: https://github.com/fwdai/hugging-face/blob/main/README.md Examples of common NLP tasks using the Inference API, including question answering, text generation, summarization, embedding, and sentiment analysis. ```ruby client.question_answering(question: 'What is my name?', context: 'I am the only child. My father named his son John.') client.text_generation(input: 'Can you please let us know more details about your ') client.summarization(input: 'The tower is 324 metres tall...') client.embedding(input: ['How to build a ruby gem?', 'How to install ruby gem?']) client.sentiment(input: ['My life sucks', 'Life is a miracle']) ``` -------------------------------- ### Summarize Text with Hugging Face API Source: https://context7.com/fwdai/hugging-face/llms.txt Demonstrates the summarization method for condensing long text passages. It includes examples of using the default summarization model and a custom one. ```ruby client = HuggingFace::InferenceApi.new(api_token: ENV['HUGGING_FACE_API_TOKEN']) long_text = 'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest man-made structure in the world, a title it held for 41 years until the Chrysler Building in New York City was finished in 1930.' # Summarize with default model result = client.summarization(input: long_text) # => [{ "summary_text" => "The Eiffel Tower is 324 metres tall and was the world's tallest structure for 41 years." }] # Using a custom summarization model result = client.summarization( input: long_text, model: 'facebook/bart-large-cnn' ) # => [{ "summary_text" => "The Eiffel Tower is 324 metres tall, making it the tallest structure in Paris..." }] ``` -------------------------------- ### Generate Text with Hugging Face API Source: https://context7.com/fwdai/hugging-face/llms.txt Illustrates the text_generation method for creating text continuations using language models. Examples show using the default model and specifying a custom model. ```ruby client = HuggingFace::InferenceApi.new(api_token: ENV['HUGGING_FACE_API_TOKEN']) # Generate text with default model result = client.text_generation( input: 'Can you please let us know more details about your ' ) # => [{ "generated_text" => "Can you please let us know more details about your project and how we can help you..." }] # Using a specific model for better results result = client.text_generation( input: 'The future of artificial intelligence is', model: 'gpt2-medium' ) # => [{ "generated_text" => "The future of artificial intelligence is bright, with advances in..." }] # Access the generated text puts result.first['generated_text'] ``` -------------------------------- ### Generate Embeddings with Hugging Face API Source: https://context7.com/fwdai/hugging-face/llms.txt Explains how to use the embedding method to generate vector representations of text inputs, which is useful for semantic search and similarity tasks. The example shows generating embeddings for multiple texts. ```ruby client = HuggingFace::InferenceApi.new(api_token: ENV['HUGGING_FACE_API_TOKEN']) # Generate embeddings for multiple texts (useful for semantic search) texts = ['How to build a ruby gem?', 'How to install ruby gem?'] result = client.embedding(input: texts) # => [ # [0.0599..., 0.1089..., 0.0346..., ...], # 384-dimensional vector for first text # [0.0512..., 0.0987..., 0.0421..., ...] # 384-dimensional vector for second text # ] ``` -------------------------------- ### Initialize Inference API Client Source: https://github.com/fwdai/hugging-face/blob/main/README.md Demonstrates how to require the library and instantiate the InferenceApi client using an authentication token. ```ruby require "hugging_face" client = HuggingFace::InferenceApi.new(api_token: ENV['HUGGING_FACE_API_TOKEN']) ``` -------------------------------- ### Initialize Hugging Face Inference API Client Source: https://context7.com/fwdai/hugging-face/llms.txt Demonstrates how to create an instance of the HuggingFace::InferenceApi client using an API token. The client handles authentication, content type, and automatic retries for API calls. ```ruby require 'hugging_face' # Initialize the client with your API token client = HuggingFace::InferenceApi.new(api_token: ENV['HUGGING_FACE_API_TOKEN']) # The client is now ready to make API calls # It automatically handles: # - Bearer token authentication # - JSON content type headers # - Automatic retries (up to 60 times) for 503 Service Unavailable responses ``` -------------------------------- ### Interact with Inference Endpoints Source: https://github.com/fwdai/hugging-face/blob/main/README.md Shows how to initialize the EndpointsApi client and make requests to custom production-grade model endpoints. ```ruby endpoint = HuggingFace::EndpointsApi.new(api_token: ENV['HUGGING_FACE_API_TOKEN']) # Question Answering request endpoint.request(endpoint_url: "https://your-end-point.url", input: { context: some_text, question: question }) # Summarization request with parameters endpoint.request(endpoint_url: "https://your-end-point.url", input: some_text, params: { min_length: 32, max_length: 64 }) ``` -------------------------------- ### Inference API Methods Source: https://github.com/fwdai/hugging-face/blob/main/README.md Methods for interacting with the free Hugging Face Inference API for rapid prototyping of ML tasks. ```APIDOC ## POST /inference/tasks ### Description Perform various machine learning tasks including question answering, text generation, summarization, embedding, and sentiment analysis using the Hugging Face Inference API. ### Method POST ### Parameters #### Request Body - **question** (string) - Optional - The question to answer (for QA task). - **context** (string) - Optional - The context for the question (for QA task). - **input** (string/array) - Required - The input text or array of texts to process. ### Request Example { "question": "What is my name?", "context": "I am the only child. My father named his son John." } ### Response #### Success Response (200) - **result** (object/string) - The model inference result. #### Response Example { "answer": "John" } ``` -------------------------------- ### Perform Question Answering with Hugging Face API Source: https://context7.com/fwdai/hugging-face/llms.txt Shows how to use the question_answering method of the HuggingFace::InferenceApi client. It supports using the default model or specifying a custom model for extracting answers from context. ```ruby client = HuggingFace::InferenceApi.new(api_token: ENV['HUGGING_FACE_API_TOKEN']) # Basic question answering with default model result = client.question_answering( question: 'What is my name?', context: 'I am the only child. My father named his son John.' ) # => { "answer" => "John", "score" => 0.98, "start" => 42, "end" => 46 } # Using a custom model result = client.question_answering( question: 'What is the capital of France?', context: 'Paris is the capital of France and its largest city.', model: 'deepset/roberta-base-squad2' ) # => { "answer" => "Paris", "score" => 0.99, "start" => 0, "end" => 5 } ``` -------------------------------- ### Interact with Inference Endpoints in Ruby Source: https://context7.com/fwdai/hugging-face/llms.txt Connects to dedicated, production-ready Inference Endpoints using a URL. Supports various tasks like question answering, summarization, and text generation with custom parameters. ```ruby endpoint = HuggingFace::EndpointsApi.new(api_token: ENV['HUGGING_FACE_API_TOKEN']) result = endpoint.request( endpoint_url: 'https://your-qa-endpoint.us-east-1.aws.endpoints.huggingface.cloud', input: { context: 'Paris is the capital of France.', question: 'What is the capital of France?' } ) result = endpoint.request( endpoint_url: 'https://your-summary-endpoint.us-east-1.aws.endpoints.huggingface.cloud', input: 'Your long document text here...', params: { min_length: 32, max_length: 64 } ) ``` -------------------------------- ### Inference Endpoints API Source: https://github.com/fwdai/hugging-face/blob/main/README.md Methods for interacting with dedicated, production-ready Inference Endpoints hosted on Hugging Face infrastructure. ```APIDOC ## POST /endpoints/request ### Description Send requests to a specific, deployed Inference Endpoint URL. This is suitable for production use cases. ### Method POST ### Parameters #### Request Body - **endpoint_url** (string) - Required - The unique URL of your deployed endpoint. - **input** (object/string) - Required - The payload required by the specific model task. - **params** (object) - Optional - Additional configuration parameters (e.g., min_length, max_length). ### Request Example { "endpoint_url": "https://your-end-point.aws.endpoints.huggingface.cloud", "input": "The tower is 324 metres tall...", "params": { "min_length": 32, "max_length": 64 } } ### Response #### Success Response (200) - **data** (object) - The inference output from the dedicated endpoint. #### Response Example { "summary_text": "The Eiffel Tower is the tallest structure in Paris." } ``` -------------------------------- ### Perform Sentiment Analysis with Ruby Source: https://context7.com/fwdai/hugging-face/llms.txt Shows how to analyze text sentiment using default or custom models. It returns labels and confidence scores for provided input strings. ```ruby client = HuggingFace::InferenceApi.new(api_token: ENV['HUGGING_FACE_API_TOKEN']) texts = ['My life sucks', 'Life is a miracle'] result = client.sentiment(input: texts) result = client.sentiment( input: ['Great service, highly recommend!'], model: 'nlptown/bert-base-multilingual-uncased-sentiment' ) ``` -------------------------------- ### Generate Embeddings and Calculate Similarity in Ruby Source: https://context7.com/fwdai/hugging-face/llms.txt Demonstrates how to generate text embeddings using the Inference API and compute cosine similarity between two vectors to determine semantic closeness. ```ruby result = client.embedding(input: 'Machine learning with Ruby') def cosine_similarity(a, b) dot_product = a.zip(b).map { |x, y| x * y }.sum magnitude_a = Math.sqrt(a.map { |x| x * x }.sum) magnitude_b = Math.sqrt(b.map { |x| x * x }.sum) dot_product / (magnitude_a * magnitude_b) end ``` -------------------------------- ### Execute Generic Model Calls in Ruby Source: https://context7.com/fwdai/hugging-face/llms.txt Utilizes the generic call method to interact with any Hugging Face model, providing flexibility for tasks not covered by specific helper methods. ```ruby client = HuggingFace::InferenceApi.new(api_token: ENV['HUGGING_FACE_API_TOKEN']) result = client.call( input: { inputs: 'What is the capital of France?' }, model: 'distilgpt2' ) result = client.call( input: { inputs: 'Translate English to French: Hello, how are you?' }, model: 't5-base' ) ``` -------------------------------- ### Handle API Errors in Ruby Source: https://context7.com/fwdai/hugging-face/llms.txt Implements exception handling for API requests, specifically addressing service unavailability and general API errors using built-in gem exception classes. ```ruby begin result = client.question_answering(question: 'What is the answer?', context: 'The answer is 42.') rescue HuggingFace::ServiceUnavailable => e puts "Service temporarily unavailable: #{e.message}" rescue HuggingFace::Error => e puts "API error: #{e.message}" end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.