Skip to content

Commit

Permalink
Cleanup linter resharper warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
ronnygunawan committed Dec 7, 2024
1 parent 7e51a91 commit a8a7047
Show file tree
Hide file tree
Showing 151 changed files with 1,920 additions and 2,534 deletions.
21 changes: 6 additions & 15 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -85,30 +85,24 @@ dotnet_naming_symbols.method_symbols.required_modifiers = async
dotnet_naming_rule.public_members_must_be_capitalized.severity = error
dotnet_naming_rule.public_members_must_be_capitalized.symbols = public_symbols
dotnet_naming_rule.public_members_must_be_capitalized.style = pascal_case_style
dotnet_naming_symbols.public_symbols.applicable_kinds = property,method,field,event,delegate
dotnet_naming_symbols.public_symbols.applicable_kinds = property,method,field,event,delegate,tuples
dotnet_naming_symbols.public_symbols.applicable_accessibilities = public,internal,protected,protected_internal
# Named tuples must be pascal case
dotnet_naming_rule.public_members_must_be_capitalized.severity = warning
dotnet_naming_rule.public_members_must_be_capitalized.symbols = named_tuples
dotnet_naming_rule.public_members_must_be_capitalized.style = pascal_case_style
dotnet_naming_symbols.named_tuples.applicable_kinds = tuples
dotnet_naming_symbols.named_tuples.applicable_accessibilities = public,internal,protected,protected_internal
# Fields must be camel case prefixed with an underscore
dotnet_naming_rule.non_public_members_must_be_underscored_camel_case.severity = warning
dotnet_naming_rule.non_public_members_must_be_underscored_camel_case.symbols = fields
dotnet_naming_rule.non_public_members_must_be_underscored_camel_case.style = underscore_camel_case_style
dotnet_naming_symbols.fields.applicable_kinds = field
dotnet_naming_symbols.fields.applicable_accessibilities = private
# Constants must be macro case
# Constants must be pascal case
dotnet_naming_rule.constant_fields_should_be_upper_case.severity = error
dotnet_naming_rule.constant_fields_should_be_upper_case.symbols = constant_fields
dotnet_naming_rule.constant_fields_should_be_upper_case.style = macro_case_style
dotnet_naming_rule.constant_fields_should_be_upper_case.style = pascal_case_style
dotnet_naming_symbols.constant_fields.applicable_kinds = field
dotnet_naming_symbols.constant_fields.required_modifiers = const
# Static readonly fields must be macro case
# Static readonly fields must be pascal case
dotnet_naming_rule.static_readonly_fields_should_be_upper_case.severity = error
dotnet_naming_rule.static_readonly_fields_should_be_upper_case.symbols = static_readonly_fields
dotnet_naming_rule.static_readonly_fields_should_be_upper_case.style = macro_case_style
dotnet_naming_rule.static_readonly_fields_should_be_upper_case.style = pascal_case_style
dotnet_naming_symbols.static_readonly_fields.applicable_kinds = field
dotnet_naming_symbols.static_readonly_fields.required_modifiers = static,readonly
# Locals must be camel case
Expand Down Expand Up @@ -153,7 +147,7 @@ csharp_style_inlined_variable_declaration = true:suggestion
# C# Formatting Rules #
###############################
# New line preferences
csharp_new_line_before_open_brace = false
csharp_new_line_before_open_brace = none
csharp_new_line_before_else = false
csharp_new_line_before_catch = false
csharp_new_line_before_finally = false
Expand Down Expand Up @@ -214,9 +208,6 @@ dotnet_diagnostic.RCS1118.severity = warning
# RCS1169: Make field read-only.
dotnet_diagnostic.RCS1169.severity = warning

# IDE0011: Add braces
csharp_prefer_braces = when_multiline:warning

# RCS1001: Add braces (when expression spans over multiple lines).
dotnet_diagnostic.RCS1001.severity = warning

Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

184 changes: 90 additions & 94 deletions BotNet.CommandHandlers/AI/Gemini/GeminiTextPromptHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,20 @@ public sealed class GeminiTextPromptHandler(
GeminiClient geminiClient,
ITelegramMessageCache telegramMessageCache,
CommandPriorityCategorizer commandPriorityCategorizer,
ICommandQueue commandQueue,
ILogger<GeminiTextPromptHandler> logger
) : ICommandHandler<GeminiTextPrompt> {
internal static readonly RateLimiter CHAT_RATE_LIMITER = RateLimiter.PerUserPerChat(5, TimeSpan.FromMinutes(5));
internal static readonly RateLimiter VIP_CHAT_RATE_LIMITER = RateLimiter.PerUserPerChat(5, TimeSpan.FromMinutes(2));
private static readonly RateLimiter ChatRateLimiter = RateLimiter.PerUserPerChat(5, TimeSpan.FromMinutes(5));
private static readonly RateLimiter VipChatRateLimiter = RateLimiter.PerUserPerChat(5, TimeSpan.FromMinutes(2));

private readonly ITelegramBotClient _telegramBotClient = telegramBotClient;
private readonly GeminiClient _geminiClient = geminiClient;
private readonly ITelegramMessageCache _telegramMessageCache = telegramMessageCache;
private readonly CommandPriorityCategorizer _commandPriorityCategorizer = commandPriorityCategorizer;
private readonly ICommandQueue _commandQueue = commandQueue;
private readonly ILogger<GeminiTextPromptHandler> _logger = logger;

public Task Handle(GeminiTextPrompt textPrompt, CancellationToken cancellationToken) {
public Task Handle(
GeminiTextPrompt textPrompt,
CancellationToken cancellationToken
) {
if (textPrompt.Command.Chat is GroupChat) {
try {
AIRateLimiters.GROUP_CHAT_RATE_LIMITER.ValidateActionRate(
AiRateLimiters.GroupChatRateLimiter.ValidateActionRate(
chatId: textPrompt.Command.Chat.Id,
userId: textPrompt.Command.Sender.Id
);
Expand All @@ -46,9 +43,7 @@ public Task Handle(GeminiTextPrompt textPrompt, CancellationToken cancellationTo
chatId: textPrompt.Command.Chat.Id,
text: $"<code>Anda terlalu banyak memanggil AI. Coba lagi {exc.Cooldown} atau lanjutkan di private chat.</code>",
parseMode: ParseMode.Html,
replyParameters: new ReplyParameters {
MessageId = textPrompt.Command.MessageId
},
replyParameters: new ReplyParameters { MessageId = textPrompt.Command.MessageId },
replyMarkup: new InlineKeyboardMarkup(
InlineKeyboardButton.WithUrl("Private chat 💬", "t.me/TeknumBot")
),
Expand All @@ -57,13 +52,13 @@ public Task Handle(GeminiTextPrompt textPrompt, CancellationToken cancellationTo
}
} else {
try {
if (textPrompt.Command.Sender is VIPSender) {
VIP_CHAT_RATE_LIMITER.ValidateActionRate(
if (textPrompt.Command.Sender is VipSender) {
VipChatRateLimiter.ValidateActionRate(
chatId: textPrompt.Command.Chat.Id,
userId: textPrompt.Command.Sender.Id
);
} else {
CHAT_RATE_LIMITER.ValidateActionRate(
ChatRateLimiter.ValidateActionRate(
chatId: textPrompt.Command.Chat.Id,
userId: textPrompt.Command.Sender.Id
);
Expand All @@ -73,101 +68,102 @@ public Task Handle(GeminiTextPrompt textPrompt, CancellationToken cancellationTo
chatId: textPrompt.Command.Chat.Id,
text: $"<code>Anda terlalu banyak memanggil AI. Coba lagi {exc.Cooldown}.</code>",
parseMode: ParseMode.Html,
replyParameters: new ReplyParameters {
MessageId = textPrompt.Command.MessageId
},
replyParameters: new ReplyParameters { MessageId = textPrompt.Command.MessageId },
cancellationToken: cancellationToken
);
}
}

// Fire and forget
Task.Run(async () => {
List<Content> messages = [
Content.FromText("user", "Act as an AI assistant. The assistant is helpful, creative, direct, concise, and always get to the point."),
Content.FromText("model", "Sure.")
];
// ReSharper disable once MethodSupportsCancellation
Task.Run(
async () => {
List<Content> messages = [
Content.FromText("user", "Act as an AI assistant. The assistant is helpful, creative, direct, concise, and always get to the point."),
Content.FromText("model", "Sure.")
];

// Merge adjacent messages from same role
foreach (MessageBase message in textPrompt.Thread.Reverse()) {
Content content = Content.FromText(
role: message.Sender.GeminiRole,
text: message.Text
);
// Merge adjacent messages from same role
foreach (MessageBase message in textPrompt.Thread.Reverse()) {
Content content = Content.FromText(
role: message.Sender.GeminiRole,
text: message.Text
);

if (messages.Count > 0
&& messages[^1].Role == message.Sender.GeminiRole) {
messages[^1].Add(content);
} else {
messages.Add(content);
if (messages.Count > 0 &&
messages[^1].Role == message.Sender.GeminiRole) {
messages[^1]
.Add(content);
} else {
messages.Add(content);
}
}
}

// Trim thread longer than 10 messages
while (messages.Count > 10) {
messages.RemoveAt(0);
}

// Thread must start with user message
while (messages.Count > 0
&& messages[0].Role != "user") {
messages.RemoveAt(0);
}
// Trim thread longer than 10 messages
while (messages.Count > 10) {
messages.RemoveAt(0);
}

// Merge user message with replied to message if thread is initiated by replying to another user
if (messages.Count > 0
&& messages[^1].Role == "user") {
messages[^1].Add(Content.FromText("user", textPrompt.Prompt));
} else {
messages.Add(Content.FromText("user", textPrompt.Prompt));
}
// Thread must start with user message
while (messages.Count > 0 &&
messages[0].Role != "user") {
messages.RemoveAt(0);
}

string response = await _geminiClient.ChatAsync(
messages: messages,
maxTokens: 512,
cancellationToken: cancellationToken
);
// Merge user message with replied to message if thread is initiated by replying to another user
if (messages.Count > 0 &&
messages[^1].Role == "user") {
messages[^1]
.Add(Content.FromText("user", textPrompt.Prompt));
} else {
messages.Add(Content.FromText("user", textPrompt.Prompt));
}

// Send response
Message responseMessage;
try {
responseMessage = await telegramBotClient.SendTextMessageAsync(
chatId: textPrompt.Command.Chat.Id,
text: response,
parseModes: [ParseMode.MarkdownV2, ParseMode.Markdown, ParseMode.Html],
replyToMessageId: textPrompt.Command.MessageId,
replyMarkup: new InlineKeyboardMarkup(
InlineKeyboardButton.WithUrl(
text: "Generated by Google Gemini 1.5 Flash",
url: "https://deepmind.google/technologies/gemini/"
)
),
string response = await geminiClient.ChatAsync(
messages: messages,
maxTokens: 512,
cancellationToken: cancellationToken
);
} catch (Exception exc) {
_logger.LogError(exc, null);
await telegramBotClient.SendMessage(
chatId: textPrompt.Command.Chat.Id,
text: "😵",
parseMode: ParseMode.Html,
replyParameters: new ReplyParameters {
MessageId = textPrompt.Command.MessageId
},
cancellationToken: cancellationToken

// Send response
Message responseMessage;
try {
responseMessage = await telegramBotClient.SendTextMessageAsync(
chatId: textPrompt.Command.Chat.Id,
text: response,
parseModes: [ParseMode.MarkdownV2, ParseMode.Markdown, ParseMode.Html],
replyToMessageId: textPrompt.Command.MessageId,
replyMarkup: new InlineKeyboardMarkup(
InlineKeyboardButton.WithUrl(
text: "Generated by Google Gemini 1.5 Flash",
url: "https://deepmind.google/technologies/gemini/"
)
),
cancellationToken: cancellationToken
);
} catch (Exception exc) {
logger.LogError(exc, null);
await telegramBotClient.SendMessage(
chatId: textPrompt.Command.Chat.Id,
text: "😵",
parseMode: ParseMode.Html,
replyParameters: new ReplyParameters { MessageId = textPrompt.Command.MessageId },
cancellationToken: cancellationToken
);
return;
}

// Track thread
telegramMessageCache.Add(
message: AiResponseMessage.FromMessage(
message: responseMessage,
replyToMessage: textPrompt.Command,
callSign: "Gemini",
commandPriorityCategorizer: commandPriorityCategorizer
)
);
return;
}

// Track thread
_telegramMessageCache.Add(
message: AIResponseMessage.FromMessage(
message: responseMessage,
replyToMessage: textPrompt.Command,
callSign: "Gemini",
commandPriorityCategorizer: _commandPriorityCategorizer
)
);
});
);

return Task.CompletedTask;
}
Expand Down
Loading

0 comments on commit a8a7047

Please sign in to comment.