95 lines
3.1 KiB
C#
95 lines
3.1 KiB
C#
using System.Net.Http;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using System.Windows;
|
|
using static YwxApp.AiChat.Services.OpenAIService;
|
|
|
|
namespace YwxApp.AiChat.Services
|
|
{
|
|
public class OllamaService : IChatService
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
private string _modelName;
|
|
|
|
public OllamaService()
|
|
{
|
|
_httpClient = new HttpClient();
|
|
}
|
|
|
|
public void Configure(string apiKey, string modelName)
|
|
{
|
|
//_httpClient.BaseAddress = new Uri(apiKey);
|
|
_modelName = modelName;
|
|
}
|
|
|
|
public async Task<string> GetResponseAsync(string prompt)
|
|
{
|
|
//var request = new
|
|
//{
|
|
// model = "deepseek-r1:1.5b",
|
|
// prompt = prompt,
|
|
// stream = false
|
|
//};
|
|
|
|
// var response = await _httpClient.PostAsJsonAsync("http://192.168.1.3:11434/api/generate", request);
|
|
// var result = await response.Content.ReadFromJsonAsync<OllamaResponse>();
|
|
|
|
// return result?.Response ?? "No response";
|
|
|
|
var request = new ChatRequest
|
|
{
|
|
Messages ={
|
|
new Message { Role = "user", Content = "你是谁" }
|
|
}
|
|
};
|
|
|
|
string json = JsonSerializer.Serialize(request, new JsonSerializerOptions
|
|
{
|
|
WriteIndented = true,
|
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
|
});
|
|
|
|
var response = await _httpClient.PostAsJsonAsync("http://192.168.1.3:11434/api/chat", request);
|
|
// var response = await _httpClient.PostAsJsonAsync("http://192.168.1.3:11434/api/generate", request);
|
|
// var result = await response.Content.ReadFromJsonAsync<OllamaResponse>();
|
|
var result = await response.Content.ReadAsStringAsync();
|
|
MessageBox.Show(result);
|
|
|
|
return "No response";
|
|
}
|
|
public class ChatRequest
|
|
{
|
|
[JsonPropertyName("messages")]
|
|
public List<Message> Messages { get; set; } = new List<Message>();
|
|
|
|
[JsonPropertyName("model")]
|
|
public string? Model { get; set; } = "deepseek-r1:1.5b"; // 默认值
|
|
|
|
[JsonPropertyName("stream")]
|
|
public bool Stream { get; set; } = false;
|
|
|
|
[JsonPropertyName("temperature")]
|
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
|
|
public double Temperature { get; set; } = 0.01;
|
|
|
|
[JsonPropertyName("max_tokens")]
|
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
|
|
public int MaxTokens { get; set; } = 1024;
|
|
}
|
|
|
|
public class Message
|
|
{
|
|
[JsonPropertyName("role")]
|
|
public string Role { get; set; } = "user";
|
|
|
|
[JsonPropertyName("content")]
|
|
public string Content { get; set; } = string.Empty;
|
|
}
|
|
|
|
private class OllamaResponse
|
|
{
|
|
public string Response { get; set; }
|
|
}
|
|
}
|
|
} |