本文旨在演示如何通过OllamaSharp NuGet包在.NET Core API中高效查询Ollama大语言模型,重点展示如何通过JSON配置文件动态设置模型参数和服务器地址,实现灵活维护的AI服务架构。
dotnet new webapi -n OllamaLLMAPI
cd OllamaLLMAPI
dotnet add package OllamaSharp
在appsettings.json
中定义动态配置参数:
{
"OllamaConfig":
{
"ModelName": "codellama", // 指定要查询的Ollama模型名称
"ServerUrl": "http://192.168.4.58:11434" // Ollama API服务地址
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using OllamaSharp;
using System.Threading.Tasks;
namespace OllamaLLMAPI.Controllers {
[ApiController]
[Route("[controller]")]
public class QueryController : ControllerBase {
private readonly OllamaClient _ollamaClient;
public QueryController(IOptions<OllamaConfig> config) { // 通过依赖注入获取配置
_ollamaClient = new OllamaClient(config.Value.ServerUrl, config.Value.ModelName);
}
[HttpGet("query/{input}")] // 定义API路由
public async Task<IActionResult> Get(string input) {
var response = await _ollamaClient.QueryAsync(input); // 执行模型查询
return Ok(response); // 返回JSON格式响应
}
}
}
代码亮点:
• OllamaClient
通过构造函数注入配置参数
• QueryAsync
方法实现非阻塞式异步调用
• IOptions<OllamaConfig>
自动绑定JSON配置
public void ConfigureServices(IServiceCollection services) {
services.Configure<OllamaConfig>(Configuration.GetSection("OllamaConfig")); // 绑定配置文件
services.AddControllers(); // 注册MVC控制器
}
[HttpGet("query")]
添加 [Authorize]
特性并集成JWT验证AspNetCoreRateLimit
限制每秒请求数ExceptionFilterAttribute
捕获模型服务异常Serilog
记录API调用详情与模型响应时间通过OllamaSharp与.NET Core的深度整合,开发者可以:
✅ 零代码修改切换不同LLM模型(如切换至lama-2-7b
)
✅ 动态配置适应生产/测试环境的多服务器部署
✅ 高性能推理借助异步IO与模型缓存机制提升吞吐量
✅ 安全合规构建符合GDPR的AI服务架构
立即实践:
🔗 OllamaSharp GitHub仓库
🔗 Ollama官方API文档
🔗 .NET HttpClient最佳实践
技术亮点保留说明:
###
→ ##
→ #
)