三分鐘掌握Ollama本地DeepSeek-R1模型及其它模型在.NET應用中的部署與應用
作者:iamrick
Microsoft.Extensions.AI - Ollama 提供了強大、靈活的 AI 集成方案,使 .NET 開發者能輕松構建智能應用程序。?
Microsoft.Extensions.AI 是一個強大的 .NET AI 集成庫,專注于為開發者提供豐富的功能,以便在 .NET 應用程序中輕松實現 AI 功能的集成。通過該庫,用戶可以方便地擴展和增強應用程序的智能化能力。本指南將深入介紹其主要特性及具體的使用方法,幫助開發者快速上手并充分利用 Ollama 提供的強大工具集。
先決條件
在開始之前,請確保滿足以下條件:
- 安裝 .NET 8 SDK
- 安裝 Visual Studio 或 VS Code
- 安裝 Ollama
Nuget 安裝包
NuGet\Install-Package [Microsoft.Extensions.AI](http://Microsoft.Extensions.AI) -Version 9.3.0-preview.1.25114.11
NuGet\Install-Package Microsoft.Extensions.AI.Ollama -Version 9.3.0-preview.1.25114.11
圖片
快速開始
模型下載
首先,使用 Ollama 下載必要的模型:
ollama pull deepseek-r1:1.5b # 聊天模型
ollama pull all-minilm:latest # 嵌入模型
基本示例集合
一、基礎聊天功能
using Microsoft.Extensions.AI;
namespace AppMicrosoftAI
{
internal class Program
{
static async Task Main(string[] args)
{
var endpoint = "http://localhost:11434/";
var modelId = "deepseek-r1:1.5b";
IChatClient client = new OllamaChatClient(endpoint, modelId: modelId);
var result = await client.GetResponseAsync("What is AI?");
Console.WriteLine(result.Message);
Console.ReadLine();
}
}
}
圖片
`ChatResponse` 類的說明:
- Choices(消息選擇列表):
- 類型:`IList`
- 包含聊天響應的消息列表
- 如果有多個響應選項,它們都會存儲在這個列表中
- 可以通過 `Message` 屬性直接訪問第一個選項
- Message(首選消息):
- 返回 `Choices` 列表中的第一條消息
- 如果沒有可用的選項,將拋出 `InvalidOperationException`
- 使用 `[JsonIgnore]` 特性標記,表示在 JSON 序列化時忽略
- ResponseId(響應標識):
- 類型:`string`
- 聊天響應的唯一標識符
- ChatThreadId(聊天線程標識):
- 類型:`string`
- 表示聊天線程的狀態標識符
- 在某些聊天實現中,可用于保持對話上下文
- 可以在后續的聊天請求中使用,以繼續對話
- ModelId(模型標識):
- 類型:`string`
- 標識生成響應的 AI 模型
- CreatedAt(創建時間):
- 類型:`DateTimeOffset`
- 聊天響應創建的時間戳
- FinishReason(完成原因):
- 類型:`ChatFinishReason`
- 指示響應生成停止的原因(例如:完成、達到長度限制)
- Usage(使用情況):
- 類型:`UsageDetails`
- 包含資源使用details(可能是令牌數、處理時間等)
- RawRepresentation(原始表示):
- 類型:`object`
- 存儲原始的底層響應對象
- 對調試或訪問特定實現的細節很有用
- 使用 `[JsonIgnore]` 特性標記
- AdditionalProperties(額外屬性):
- 類型:`AdditionalPropertiesDictionary`
- 允許存儲未在類中顯式定義的額外屬性
二、 對話歷史管理
using Microsoft.Extensions.AI;
namespace AppMicrosoftAI
{
internal class Program
{
static async Task Main(string[] args)
{
var endpoint = "http://localhost:11434/";
var modelId = "deepseek-r1:1.5b";
IChatClient client = new OllamaChatClient(endpoint, modelId: modelId);
List<ChatMessage> conversation =
[
new(ChatRole.System, "You are a helpful AI assistant"),
new(ChatRole.User, "What is AI?")
];
Console.WriteLine(await client.GetResponseAsync(conversation));
Console.ReadLine();
}
}
}
三、流式響應處理
using Microsoft.Extensions.AI;
namespace AppMicrosoftAI
{
internal class Program
{
static async Task Main(string[] args)
{
var endpoint = "http://localhost:11434/";
var modelId = "deepseek-r1:1.5b";
IChatClient client = new OllamaChatClient(endpoint, modelId: modelId);
await foreach (var update in client.GetStreamingResponseAsync("什么是AI?"))
{
Console.Write(update);
}
Console.WriteLine();
Console.ReadKey();
}
}
}
圖片
圖片
中間件支持
- 緩存中間件:提供響應緩存
- OpenTelemetry:性能監控和追蹤
- 工具調用中間件:擴展 AI 功能
工具調用
using System.ComponentModel;
using Microsoft.Extensions.AI;
namespace AppMicrosoftAI
{
internal class Program
{
static async Task Main(string[] args)
{
[Description("Gets the weather")]
string GetWeather() => Random.Shared.NextDouble() > 0.5 ? "It's sunny" : "It's raining";
var chatOptions = new ChatOptions
{
Tools = [AIFunctionFactory.Create(GetWeather)]
};
var endpoint = "http://localhost:11434/";
var modelId = "qwen2.5:3b";
IChatClient client = new OllamaChatClient(endpoint, modelId: modelId)
.AsBuilder()
.UseFunctionInvocation()
.Build();
Console.WriteLine(await client.GetResponseAsync("你需要雨傘嗎?", chatOptions));
Console.ReadKey();
}
}
}
使用提示緩存中間件
using System.ComponentModel;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
namespace AppMicrosoftAI
{
internal class Program
{
static async Task Main(string[] args)
{
var endpoint = "http://localhost:11434/";
var modelId = "deepseek-r1:1.5b";
var options = Options.Create(new MemoryDistributedCacheOptions());
IDistributedCache cache = new MemoryDistributedCache(options);
IChatClient client = new OllamaChatClient(endpoint, modelId: modelId)
.AsBuilder()
.UseDistributedCache(cache)
.Build();
string[] prompts = ["What is AI?", "What is .NET?", "What is AI?"];
foreach (var prompt in prompts)
{
await foreach (var message in client.GetStreamingResponseAsync(prompt))
{
Console.Write(message);
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
Middleware
using System.ComponentModel;
using System.Diagnostics;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using OpenTelemetry.Trace;
namespace AppMicrosoftAI
{
internal class Program
{
static async Task Main(string[] args)
{
var sourceName = Guid.NewGuid().ToString();
var activities = new List<Activity>();
var tracerProvider = OpenTelemetry.Sdk.CreateTracerProviderBuilder()
.AddInMemoryExporter(activities)
.AddSource(sourceName)
.Build();
[Description("Gets the weather")]
string GetWeather() => Random.Shared.NextDouble() > 0.5 ? "It's sunny" : "It's raining";
var chatOptions = new ChatOptions
{
Tools = [AIFunctionFactory.Create(GetWeather)]
};
var endpoint = "http://localhost:11434/";
var modelId = "qwen2.5:3b";
var options = Options.Create(new MemoryDistributedCacheOptions());
IDistributedCache cache = new MemoryDistributedCache(options);
IChatClient client = new OllamaChatClient(endpoint, modelId: modelId)
.AsBuilder()
.UseFunctionInvocation()
.UseOpenTelemetry(sourceName: sourceName, configure: o => o.EnableSensitiveData = true)
.UseDistributedCache(cache)
.Build();
List<ChatMessage> conversation =
[
new(ChatRole.System, "You are a helpful AI assistant"),
new(ChatRole.User, "需要帶雨傘嗎?")
];
Console.WriteLine(await client.GetResponseAsync("需要帶雨傘嗎?", chatOptions));
Console.ReadKey();
}
}
}
文本嵌入
using System.ComponentModel;
using Microsoft.Extensions.AI;
namespace AppMicrosoftAI
{
internal class Program
{
static async Task Main(string[] args)
{
var endpoint = "http://localhost:11434/";
var modelId = "all-minilm:latest";
IEmbeddingGenerator<string, Embedding<float>> generator = new OllamaEmbeddingGenerator(endpoint, modelId: modelId);
var embedding = await generator.GenerateEmbeddingVectorAsync("What is AI?");
Console.WriteLine(string.Join(", ", embedding.ToArray()));
Console.ReadKey();
}
}
}
圖片
最佳實踐
- 使用依賴注入管理 AI 客戶端
- 實現適當的錯誤處理
- 管理對話歷史
- 利用中間件增強功能
結論
Microsoft.Extensions.AI - Ollama 提供了強大、靈活的 AI 集成方案,使 .NET 開發者能輕松構建智能應用程序。
責任編輯:武曉燕
來源:
技術老小子