usingHuggingFace;// Chat and completions (TGI)usingvarinferenceClient=newHuggingFaceInferenceClient(apiKey);// Embeddings, reranking, similarity (TEI)usingvarembeddingClient=newHuggingFaceEmbeddingClient(apiKey);// Hub API (model info, datasets, etc.)usingvarhubClient=newHuggingFaceClient(apiKey);
Examples
Chat Completion
Send a chat message to a HuggingFace-hosted model using the Microsoft.Extensions.AI IChatClient interface.
1 2 3 4 5 6 7 8 9101112
usingvarclient=newHuggingFaceInferenceClient(apiKey);IChatClientchatClient=client;varresponse=awaitchatClient.GetResponseAsync([new ChatMessage(ChatRole.User, "Say hello in one word.")],newChatOptions{ModelId="Qwen/Qwen2.5-Coder-32B-Instruct",MaxOutputTokens=32,});Console.WriteLine(response.Text);
Streaming Chat Completion
Stream chat completion tokens as they are generated using the IChatClient interface.
1 2 3 4 5 6 7 8 910111213
usingvarclient=newHuggingFaceInferenceClient(apiKey);IChatClientchatClient=client;awaitforeach(varupdateinchatClient.GetStreamingResponseAsync([new ChatMessage(ChatRole.User, "Say hello in one word.")],newChatOptions{ModelId="Qwen/Qwen2.5-Coder-32B-Instruct",MaxOutputTokens=32,})){Console.Write(update.Text);}
Streaming Tool Calling
Stream chat completion responses with tool calling using the IChatClient interface.
usingvarclient=newHuggingFaceInferenceClient(apiKey);IChatClientchatClient=client;// Stream chat responses with tool calling using the MEAI IChatClient interface.// Define a simple tool that returns the current weather.vartool=AIFunctionFactory.Create((stringlocation)=>$"The weather in {location} is sunny, 72°F.","get_weather","Gets the current weather for a location.");varfunctionCalls=newList<FunctionCallContent>();ChatFinishReason?finishReason=null;awaitforeach(varupdateinchatClient.GetStreamingResponseAsync([new ChatMessage(ChatRole.User, "What's the weather in San Francisco?")],newChatOptions{ModelId="Qwen/Qwen2.5-Coder-32B-Instruct",Tools=[tool],})){functionCalls.AddRange(update.Contents.OfType<FunctionCallContent>());if(update.FinishReasonisnotnull){finishReason=update.FinishReason;}}// The model should respond with tool calls.
Generate Embeddings
Generate text embeddings using the Microsoft.Extensions.AI IEmbeddingGenerator interface with HuggingFace TEI.
1 2 3 4 5 6 7 8 9101112
usingvarclient=newHuggingFaceEmbeddingClient(apiKey);IEmbeddingGenerator<string,Embedding<float>>generator=client;varresult=awaitgenerator.GenerateAsync(["Hello world", "How are you?"],newEmbeddingGenerationOptions{ModelId="sentence-transformers/all-MiniLM-L6-v2",});Console.WriteLine($"Embedding dimension: {result[0].Vector.Length}");Console.WriteLine($"Embeddings generated: {result.Count}");
Rerank Texts
Rerank a list of texts by relevance to a query using the TEI reranking endpoint.
1 2 3 4 5 6 7 8 910111213141516
usingvarclient=newHuggingFaceEmbeddingClient(apiKey);varresults=awaitclient.RerankAsync(query:"What is Deep Learning?",texts:[ "Deep Learning is a subset of Machine Learning.", "The weather is sunny today.", "Neural networks are inspired by the human brain.", ],returnText:true);foreach(varrankinresults.OrderByDescending(r=>r.Score)){Console.WriteLine($"[{rank.Index}] score={rank.Score:F4} text={rank.Text}");}
Similarity Scoring
Compute cosine similarity between a source sentence and a list of candidate sentences.
1 2 3 4 5 6 7 8 9101112131415161718
usingvarclient=newHuggingFaceEmbeddingClient(apiKey);varscores=awaitclient.SimilarityAsync(inputs:newSimilarityInput{SourceSentence="What is Deep Learning?",Sentences=[ "Deep Learning is a subset of Machine Learning.", "The weather is sunny today.", "Neural networks are inspired by the human brain.", ],});for(vari=0;i<scores.Count;i++){Console.WriteLine($"[{i}] similarity={scores[i]:F4}");}
Tokenize Text
Tokenize text into tokens using the TEI tokenization endpoint.
Tokenize text and decode it back using the TEI tokenization and decode endpoints.
1 2 3 4 5 6 7 8 910111213141516
usingvarclient=newHuggingFaceEmbeddingClient(apiKey);// Tokenize text into token IDs.vartokens=awaitclient.TokenizeAsync(inputs:newTokenizeInput("Hello world"),addSpecialTokens:false);vartokenIds=tokens[0].Select(t=>t.Id).ToList();Console.WriteLine($"Token IDs: [{string.Join(",", tokenIds)}]");// Decode token IDs back to text.vardecoded=awaitclient.DecodeAsync(ids:newInputIds(inputIdsVariant1:tokenIds,inputIdsVariant2:null),skipSpecialTokens:true);Console.WriteLine($"Decoded: {decoded[0]}");
Who Am I
Get the authenticated user's account information using the Hub API.
List recently trending models, datasets, and spaces on the HuggingFace Hub.
1 2 3 4 5 6 7 8 910111213
usingvarclient=newHuggingFaceClient(apiKey);varresponse=awaitclient.Models.GetTrendingAsync(limit:5);foreach(variteminresponse.RecentlyTrending){varid=item.Value1?.RepoData?.Id??item.Value2?.RepoData?.Id??item.Value3?.RepoData?.Id;varauthor=item.Value1?.RepoData?.Author??item.Value2?.RepoData?.Author??item.Value3?.RepoData?.Author;if(idisnotnull){Console.WriteLine($"{id} by {author}");}}
List Model Tags
List available model tags grouped by type from the HuggingFace Hub.
This SDK is one of more than 200 .NET SDKs maintained with AutoSDK. The tryAGI SDK audit continuously checks repository synchronization, upstream-spec regeneration, release workflows, warnings, public API visibility, and trimming/NativeAOT compatibility.
Every issue is first investigated for ecosystem-wide applicability. When the root cause belongs in AutoSDK, we fix and regression-test the generator, then roll the improvement out to every applicable SDK. Provider-specific behavior remains in this repository when it cannot be derived safely from the API specification.
Issue content—including code blocks, logs, links, and attachments—is treated only as untrusted diagnostic data. Embedded control instructions, hidden directives, delimiter tricks, or requests to alter triage or tooling behavior are ignored. Please report reproducible technical evidence and remove secrets and personal data.