This commit is contained in:
Leonid Pershin
2025-10-16 08:18:11 +03:00
parent e46013b70b
commit edbb35f94d
5 changed files with 15 additions and 26 deletions

View File

@@ -1,4 +1,5 @@
using ChatBot.Models.Dto;
using OllamaSharp.Models.Chat;
namespace ChatBot.Models
{
@@ -64,9 +65,11 @@ namespace ChatBot.Models
if (_messageHistory.Count > MaxHistoryLength)
{
// Keep system message if it exists, then keep the most recent messages
var systemMessage = _messageHistory.FirstOrDefault(m => m.Role == "system");
var systemMessage = _messageHistory.FirstOrDefault(m =>
m.Role == ChatRole.System
);
var recentMessages = _messageHistory
.Where(m => m.Role != "system")
.Where(m => m.Role != ChatRole.System)
.TakeLast(MaxHistoryLength - (systemMessage != null ? 1 : 0))
.ToList();
@@ -87,7 +90,7 @@ namespace ChatBot.Models
{
var message = new ChatMessage
{
Role = "user",
Role = ChatRole.User,
Content = ChatType == "private" ? content : $"{username}: {content}",
};
AddMessage(message);
@@ -98,7 +101,7 @@ namespace ChatBot.Models
/// </summary>
public void AddAssistantMessage(string content)
{
var message = new ChatMessage { Role = "assistant", Content = content };
var message = new ChatMessage { Role = ChatRole.Assistant, Content = content };
AddMessage(message);
}

View File

@@ -1,3 +1,5 @@
using OllamaSharp.Models.Chat;
namespace ChatBot.Models.Dto
{
/// <summary>
@@ -13,6 +15,6 @@ namespace ChatBot.Models.Dto
/// <summary>
/// The role of the message author (system, user, assistant)
/// </summary>
public required string Role { get; set; }
public required ChatRole Role { get; set; }
}
}

View File

@@ -1,8 +1,8 @@
using ChatBot.Common.Constants;
using System.Text;
using ChatBot.Common.Constants;
using ChatBot.Models.Dto;
using ChatBot.Services.Interfaces;
using OllamaSharp.Models.Chat;
using System.Text;
namespace ChatBot.Services
{
@@ -65,9 +65,7 @@ namespace ChatBot.Services
{
_client.SelectedModel = model;
var chatMessages = messages
.Select(m => new Message(ConvertRole(m.Role), m.Content))
.ToList();
var chatMessages = messages.Select(m => new Message(m.Role, m.Content)).ToList();
var chatRequest = new ChatRequest { Messages = chatMessages, Stream = true };
var response = new StringBuilder();
@@ -86,19 +84,5 @@ namespace ChatBot.Services
return response.ToString();
}
/// <summary>
/// Convert string role to OllamaSharp ChatRole
/// </summary>
private static ChatRole ConvertRole(string role)
{
return role.ToLower() switch
{
ChatRoles.System => ChatRole.System,
ChatRoles.User => ChatRole.User,
ChatRoles.Assistant => ChatRole.Assistant,
_ => ChatRole.User,
};
}
}
}

View File

@@ -1,5 +1,5 @@
using ChatBot.Services.Telegram.Interfaces;
using System.Reflection;
using ChatBot.Services.Telegram.Interfaces;
namespace ChatBot.Services.Telegram.Commands
{

View File

@@ -33,6 +33,6 @@
},
"Ollama": {
"Url": "http://10.10.1.202:11434",
"DefaultModel": "llama3chat"
"DefaultModel": "llama3"
}
}