C# Semantic Kernel 最簡單、免費使用 LLM 示範 (Hugging Face)

Semantic Kernel 是 Microsoft 的一個開源專案,是用來簡化我們呼叫各大 LLM (大型語言模型)的工具,也可以很輕鬆的建立擴充套件(Plugin)讓 LLM 使用,讓我們不用很繁瑣的自己手刻 API 呼叫,要更換不同的 LLM 非常方便,並且支援 C#, Python, Java。

Semantic Kernel 預設可以呼叫 OpenAI 和 Azure OpenAI ,不過這些都需要付費,對於剛開始入門的 LLM 新手來說想要練習還是有一定的門檻(需要信用卡、需要越來越多的 $$ 使用 API)。不過還好 Semantic Kernel 也可以使用本地部屬的模型或是其他第三方服務,並且加上一個套件就可以輕鬆的透過 Hugging Face 免費使用其他大神的模型(需要註冊帳號,不過不需要信用卡 連帳號都不需要了),本篇就來示範一下該如何從零開始使用大語言模型。

安裝

先使用 NuGet 安裝 Microsoft.SemanticKernel 套件,或是使用 .NET CLI 執行以下指令安裝
	
dotnet add package Microsoft.SemanticKernel --version 1.1.0
    

因為要使用免費的 Hugging Face ,所以需要額外安裝 Microsoft.SemanticKernel.Connectors.HuggingFace 套件:
	
dotnet add package Microsoft.SemanticKernel.Connectors.HuggingFace --version 1.1.0-preview
    

選擇 Hugging Face 上的免費模型

開啟 HuggingChat 網頁,將 Current Model 下面的這個文字複製起來,這個是現在使用的模型的名稱,等一下要放在程式裡使用

在撰文的當下筆者看到的是下面這個模型,撰文測試時可以免費使用,不需要 apiKey
    
mistralai/Mixtral-8x7B-Instruct-v0.1
    

使用示範

筆者一開始練習時複製並建立了其他模型來使用,測試一段時間後開始寫文章, 原本截了許多張圖片,從 Hugging Face 註冊帳號到產生 API step by step 的介紹了一遍,然後使用公開模型做示範,突然想到說該不會公開模型不用 apiKey 吧?結果測試了一下還真的不需要...於是就把那些步驟從文章中移除了...

下面的程式碼是 Semantic Kernel 官方的範例,筆者改為使用 Hugging Face 的免費模型後再做了一些修改,程式碼如下:
    
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.OpenAI;

var builder = Kernel.CreateBuilder();

#pragma warning disable SKEXP0020
builder.AddHuggingFaceTextGeneration("mistralai/Mixtral-8x7B-Instruct-v0.1"); // 剛剛複製的模型名稱

var kernel = builder.Build();

var template = @"{{$input}}

將上面的內容翻譯成正體中文"; // 提示詞

var prompt =
    kernel.CreateFunctionFromPrompt(template, executionSettings: new OpenAIPromptExecutionSettings { MaxTokens = 100 });

// 第一個輸入內容
string text1 = @"
1st Law of Thermodynamics - Energy cannot be created or destroyed.
2nd Law of Thermodynamics - For a spontaneous process, the entropy of the universe increases.
3rd Law of Thermodynamics - A perfect crystal at zero Kelvin has zero entropy.";

// 第二個輸入內容
string text2 = @"
1. An object at rest remains at rest, and an object in motion remains in motion at constant speed and in a straight line unless acted on by an unbalanced force.
2. The acceleration of an object depends on the mass of the object and the amount of force applied.
3. Whenever one object exerts a force on another object, the second object exerts an equal and opposite on the first.";

// 替換提示詞裡輸入的內容傳送並顯示回應
Console.WriteLine(await kernel.InvokeAsync(prompt, new() { ["input"] = text1 }));
Console.WriteLine(await kernel.InvokeAsync(prompt, new() { ["input"] = text2 }));
    

回應內容:
    
// 回應一:

1st Law of Thermodynamics - Energy cannot be created or destroyed.
2nd Law of Thermodynamics - For a spontaneous process, the entropy of the universe increases.
3rd Law of Thermodynamics - A perfect crystal at zero Kelvin has zero entropy.

將上面的內容翻譯成正體中文:

1 法則:能量無法創造或摧毀。
2 法則:自發過程中,宇宙的熵增加。
3 法則:零度克勞億(0 Kelvin)的完美結晶沒有熵。


// 回應二:

The first law of thermodynamics
1. An object at rest remains at rest, and an object in motion remains in motion at constant speed and in a straight line unless acted on by an unbalanced force.
2. The acceleration of an object depends on the mass of the object and the amount of force applied.
3. Whenever one object exerts a force on another object, the second object exerts an equal and opposite on the first.

將上面的內容翻譯成正體中文:

1. 靜止的物體保持靜止,運動中的物體保持不變的速度和直線運動,除非受到不平衡的力.
2. 物體的加速度取決於物體的質量和應用的力量。
3. 每當一個物體對另一個物體施加力時,第二個物體就會對第一個物體施加大小相等且方向相反的力。
    

需要注意的是原本會有編號為 SKEXP0020 的警告,警告內容如下:
    
0>Program.cs(19,1): Error SKEXP0020 : 'Microsoft.SemanticKernel.HuggingFaceKernelBuilderExtensions.AddHuggingFaceTextGeneration(Microsoft.SemanticKernel.IKernelBuilder, string, string?, string?, string?, System.Net.Http.HttpClient?)' 僅供評估之用,可能會在未來更新中變更或移除。抑制此診斷以繼續。
0>------- Finished building project: ConsoleAppSemanticKernelTest0124. Succeeded: False. Errors: 1. Warnings: 0
    

代表 AddHuggingFaceTextGeneration 這個方法並沒有正式發布,未來可能會更改,需要使用下面這個程式碼告訴編譯器我們知道了,請忽略這個警告:
    
#pragma warning disable SKEXP0020
    

不過畢竟是免費的模型,和 GPT-4 等其他 LLM 相比還是不夠「聰明」,應該只能拿來練習,如果要能夠正常使用、提高準確度和使用 Plugin,可能還是要使用大公司的商用模型..

參考資料:
GitHub - microsoft/semantic-kernel
Microsoft.Learn - HuggingFaceKernelBuilderExtensions Class
Microsoft.DevBlogs - How to use Hugging Face Models with Semantic Kernel (python)
Microsoft.DevBlogs - Say hello to Semantic Kernel V1.0.1
GitHub issuse - .Net GoogleAI connector progress (Gemini) #4680

留言

張貼留言

如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com