netCore 代码接入Ollama通过OllamaApi

net 代码接入Ollama (已测试ok)=》通过OllamaApi方式访问调用接入对话
=》配置类:appsettings.json=>新增 “OllamaApi”

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "OllamaApi": {
    "BaseUrl": "http://127.0.0.1:11434", //"https://api.ollama.com",
    "ApiKey": "A0D75JC-DK2M6FE-JKGCZE9-FTP9Q30"
  }
}

=》OllamaService.cs Ollama服务类

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class OllamaService
{
    private readonly HttpClient _httpClient;
    private readonly string _baseUrl;
    private readonly ILogger<OllamaService> _logger;
    private readonly string _apiKey;

    public OllamaService(HttpClient httpClient, IConfiguration configuration, ILogger<OllamaService> logger)
    {
        _httpClient = httpClient;
        _baseUrl = configuration["OllamaApi:BaseUrl"];
        _apiKey = configuration["OllamaApi:ApiKey"];
        _logger = logger;

        _httpClient.BaseAddress = new Uri(_baseUrl);
        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> GetResponseAsync(string model, string input)
    {
        var request = new
        {
            model = model,
            prompt = input,// input = input
            stream = false
        };

        var json = JsonSerializer.Serialize(request);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        _logger.LogInformation($"Sending request to Ollama API: {json}");

        var response = await _httpClient.PostAsync("/api/generate", content);

        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            _logger.LogError($"Error from Ollama API: {response.StatusCode} - {errorContent}");
            return $"Error: {response.StatusCode} - {errorContent}";
        }

        var responseContent = await response.Content.ReadAsStringAsync();
        _logger.LogInformation($"Response from Ollama API: {responseContent}");

        var result = JsonSerializer.Deserialize<OllamaResponse>(responseContent);

        if (result == null)
        {
            _logger.LogWarning("Failed to deserialize Ollama response.");
        }

        return result?.response ?? "No response from Ollama";
    }
}

public class OllamaResponse
{
    public string response { get; set; }
}

=》program.cs 里面注册OllamaService实例Program.cs负责配置和启动应用程序 

            // Add HttpClient and OllamaService
            builder.Services.AddHttpClient<OllamaService>(client =>
            {
                client.BaseAddress = new Uri(builder.Configuration["OllamaApi:BaseUrl"]);
                client.Timeout = TimeSpan.FromMinutes(5); // 增加超时时间到 5 分钟
            });

            builder.Services.AddSingleton<IConfiguration>(builder.Configuration);
            builder.Services.AddScoped<OllamaService>();
            // Add logging
            builder.Services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.ClearProviders();
                loggingBuilder.AddConsole();
                loggingBuilder.AddDebug();
            });
=>Index.cshtml 页面UI

```html
cshtml
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <h1 class="display-4">Ollama Model Selection</h1>
    <form method="post">
            <div class="form-group">
                <label for="modelSelect">Select Ollama Model:</label>
                <select class="form-control" id="modelSelect" asp-for="SelectedModel" asp-items="Model.Models">
                    <option value="1">--Select Model--</option>
                </select>
            </div>
            <div class="form-group">
                <label for="inputText">Input Text:</label>
                <textarea class="form-control" id="inputText" asp-for="InputText" rows="3"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
        <div class="form-group mt-3">
            <label for="resultText">Result:</label>
            <textarea class="form-control" id="resultText" asp-for="ResultText" rows="5" readonly></textarea>
        </div>
</div>
<script>
    body {
        font - family: Arial, sans - serif;
        margin: 20px;
    }

h1 {
        color: #333;
    }

.form - group {
        margin - bottom: 15px;
    }

textarea {
        resize: vertical;
    }
</script>

   
=>Index.cshtml.cs 调用ollamaservice实例方法

   

```csharp
 public class IndexModel : PageModel
    {
        private readonly OllamaService _ollamaService;
        public List<SelectListItem> Models { get; set; }
        [BindProperty]
        public string SelectedModel { get; set; }
        [BindProperty]
        public string InputText { get; set; }
        [BindProperty]
        public string ResultText { get; set; }

        public IndexModel(OllamaService ollamaService)
        {
            _ollamaService = ollamaService;
            Models = new List<SelectListItem>
            {
                new SelectListItem { Value = "deepseek-r1:7b", Text = "deepseek-r1" },
                new SelectListItem { Value = "qwen2.5:7b", Text = "qwen2.5" },
                new SelectListItem { Value = "model3", Text = "Model 3" }
            };
        }

        public void OnGet()
        {
           
        }
        public async Task<IActionResult> OnPostAsync()
        {
            if (!string.IsNullOrEmpty(SelectedModel) && !string.IsNullOrEmpty(InputText))
            {
                ResultText = await _ollamaService.GetResponseAsync(SelectedModel, InputText);
            }
            else
            {
                ResultText = "Please select a model and enter input text.";
            }

            return Page();
        }

        //public void OnPost()
        //{
        //    // 这里可以添加处理逻辑,例如调用 Ollama 模型并获取结果
        //    // 为了示例,我们假设调用了一个静态方法
        //    ResultText = ProcessInput(SelectedModel, InputText);
        //}

        //private string ProcessInput(string model, string input)
        //{
        //    // 模拟调用 Ollama 模型
        //    return $"You selected model: {model} and input text: {input}";
        //}
    }

2.效果展示
在这里插入图片描述
关注我的抖音号,获取更多相关内容!
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值