Skip to content

Commit 149de9a

Browse files
103048103048
authored andcommitted
Code improvement based on feedback.
1 parent 6abc7ab commit 149de9a

File tree

8 files changed

+114
-116
lines changed

8 files changed

+114
-116
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
namespace BotSharp.Abstraction.Email.Settings;
2+
3+
public class EmailHandlerSettings
4+
{
5+
public string EmailAddress { get; set; } = string.Empty;
6+
public string Name { get; set; } = string.Empty;
7+
public string Username { get; set; } = string.Empty;
8+
public string Password { get; set; } = string.Empty;
9+
public string SMTPServer { get; set; } = string.Empty;
10+
public int SMTPPort { get; set; }
11+
}

src/Infrastructure/BotSharp.Abstraction/Email/Settings/EmailPluginSettings.cs

Lines changed: 0 additions & 12 deletions
This file was deleted.

src/Plugins/BotSharp.Plugin.EmailHandler/BotSharp.Plugin.EmailHandler.csproj

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,15 @@
1111
</PropertyGroup>
1212

1313
<ItemGroup>
14-
<None Remove="data\agents\00000000-0000-0000-0000-000000000000\functions\handle_email_request.json" />
15-
<None Remove="data\agents\00000000-0000-0000-0000-000000000000\templates\handle_email_request.fn.liquid" />
14+
<None Remove="data\agents\6745151e-6d46-4a02-8de4-1c4f21c7da95\functions\handle_email_request.json" />
15+
<None Remove="data\agents\6745151e-6d46-4a02-8de4-1c4f21c7da95\templates\handle_email_request.fn.liquid" />
1616
</ItemGroup>
1717

1818
<ItemGroup>
19-
<Content Include="data\agents\00000000-0000-0000-0000-000000000000\functions\handle_email_request.json">
19+
<Content Include="data\agents\6745151e-6d46-4a02-8de4-1c4f21c7da95\functions\handle_email_request.json">
2020
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
2121
</Content>
22-
<Content Include="data\agents\00000000-0000-0000-0000-000000000000\templates\handle_email_request.fn.liquid">
22+
<Content Include="data\agents\6745151e-6d46-4a02-8de4-1c4f21c7da95\templates\handle_email_request.fn.liquid">
2323
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
2424
</Content>
2525
</ItemGroup>

src/Plugins/BotSharp.Plugin.EmailHandler/EmailHandlerPlugin.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public void RegisterDI(IServiceCollection services, IConfiguration config)
2323
services.AddScoped(provider =>
2424
{
2525
var settingService = provider.GetRequiredService<ISettingService>();
26-
return settingService.Bind<EmailPluginSettings>("EmailPlugin");
26+
return settingService.Bind<EmailHandlerSettings>("EmailHandler");
2727
});
2828

2929
services.AddScoped<IAgentHook, EmailHandlerHook>();
Lines changed: 59 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,78 @@
11
using BotSharp.Abstraction.Email.Settings;
22
using BotSharp.Plugin.EmailHandler.LlmContexts;
3+
using MailKit;
34
using MailKit.Net.Smtp;
45
using MailKit.Security;
56
using Microsoft.AspNetCore.Http;
67
using Microsoft.Extensions.Logging;
78
using MimeKit;
89
using System.Net.Http;
910

10-
namespace BotSharp.Plugin.EmailHandler.Functions
11+
namespace BotSharp.Plugin.EmailHandler.Functions;
12+
13+
public class HandleEmailRequestFn : IFunctionCallback
1114
{
12-
public class HandleEmailRequestFn : IFunctionCallback
13-
{
14-
public string Name => "handle_email_request";
15-
public string Indication => "Handling email request";
15+
public string Name => "handle_email_request";
16+
public string Indication => "Handling email request";
1617

17-
private readonly IServiceProvider _services;
18-
private readonly ILogger<HandleEmailRequestFn> _logger;
19-
private readonly IHttpClientFactory _httpClientFactory;
20-
private readonly IHttpContextAccessor _context;
21-
private readonly BotSharpOptions _options;
22-
private readonly EmailPluginSettings _emailSettings;
18+
private readonly IServiceProvider _services;
19+
private readonly ILogger<HandleEmailRequestFn> _logger;
20+
private readonly IHttpClientFactory _httpClientFactory;
21+
private readonly IHttpContextAccessor _context;
22+
private readonly BotSharpOptions _options;
23+
private readonly EmailHandlerSettings _emailSettings;
2324

24-
public HandleEmailRequestFn(IServiceProvider services,
25-
ILogger<HandleEmailRequestFn> logger,
26-
IHttpClientFactory httpClientFactory,
27-
IHttpContextAccessor context,
28-
BotSharpOptions options,
29-
EmailPluginSettings emailPluginSettings)
30-
{
31-
_services = services;
32-
_logger = logger;
33-
_httpClientFactory = httpClientFactory;
34-
_context = context;
35-
_options = options;
36-
_emailSettings = emailPluginSettings;
37-
}
38-
public async Task<bool> Execute(RoleDialogModel message)
39-
{
40-
var args = JsonSerializer.Deserialize<LlmContextIn>(message.FunctionArgs, _options.JsonSerializerOptions);
41-
var recipient = args?.ToAddress;
42-
var body = args?.Content;
43-
var subject = args?.Subject;
25+
public HandleEmailRequestFn(IServiceProvider services,
26+
ILogger<HandleEmailRequestFn> logger,
27+
IHttpClientFactory httpClientFactory,
28+
IHttpContextAccessor context,
29+
BotSharpOptions options,
30+
EmailHandlerSettings emailPluginSettings)
31+
{
32+
_services = services;
33+
_logger = logger;
34+
_httpClientFactory = httpClientFactory;
35+
_context = context;
36+
_options = options;
37+
_emailSettings = emailPluginSettings;
38+
}
39+
public async Task<bool> Execute(RoleDialogModel message)
40+
{
41+
var args = JsonSerializer.Deserialize<LlmContextIn>(message.FunctionArgs, _options.JsonSerializerOptions);
42+
var recipient = args?.ToAddress;
43+
var body = args?.Content;
44+
var subject = args?.Subject;
4445

45-
try
46-
{
47-
var mailMessage = new MimeMessage();
48-
mailMessage.From.Add(new MailboxAddress(_emailSettings.Name, _emailSettings.EmailAddress));
49-
mailMessage.To.Add(new MailboxAddress("", recipient));
50-
mailMessage.Subject = subject;
51-
mailMessage.Body = new TextPart("plain")
52-
{
53-
Text = body
54-
};
55-
await HandleSendEmailBySMTP(mailMessage);
56-
message.Content = $"Email successfully send over to {recipient}. Email Subject: {subject}";
57-
return true;
58-
}
59-
catch (Exception ex)
46+
try
47+
{
48+
var mailMessage = new MimeMessage();
49+
mailMessage.From.Add(new MailboxAddress(_emailSettings.Name, _emailSettings.EmailAddress));
50+
mailMessage.To.Add(new MailboxAddress("", recipient));
51+
mailMessage.Subject = subject;
52+
mailMessage.Body = new TextPart("plain")
6053
{
61-
var msg = $"Failed to send the email. {ex.Message}";
62-
_logger.LogWarning($"{msg}\n(Error: {ex.Message})");
63-
message.Content = msg;
64-
return false;
65-
}
54+
Text = body
55+
};
56+
var response = await HandleSendEmailBySMTP(mailMessage);
57+
_logger.LogWarning($"Email successfully send over to {recipient}. Email Subject: {subject} [{response}]");
58+
message.Content = response;
59+
return true;
6660
}
67-
public async Task HandleSendEmailBySMTP(MimeMessage mailMessage)
61+
catch (Exception ex)
6862
{
69-
using (var smtpClient = new SmtpClient())
70-
{
71-
await smtpClient.ConnectAsync(_emailSettings.SMTPServer, _emailSettings.SMTPPort, SecureSocketOptions.StartTls);
72-
await smtpClient.AuthenticateAsync(_emailSettings.EmailAddress, _emailSettings.Password);
73-
await smtpClient.SendAsync(mailMessage);
74-
smtpClient.Disconnect(true);
75-
}
63+
var msg = $"Failed to send the email. {ex.Message}";
64+
_logger.LogError($"{msg}\n(Error: {ex.Message})");
65+
message.Content = msg;
66+
return false;
7667
}
7768
}
69+
70+
public async Task<string> HandleSendEmailBySMTP(MimeMessage mailMessage)
71+
{
72+
using var smtpClient = new SmtpClient();
73+
await smtpClient.ConnectAsync(_emailSettings.SMTPServer, _emailSettings.SMTPPort, SecureSocketOptions.StartTls);
74+
await smtpClient.AuthenticateAsync(_emailSettings.EmailAddress, _emailSettings.Password);
75+
var response = await smtpClient.SendAsync(mailMessage);
76+
return response;
77+
}
7878
}
Lines changed: 39 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using BotSharp.Abstraction.Agents;
2+
using BotSharp.Abstraction.Agents.Enums;
23
using BotSharp.Abstraction.Agents.Settings;
34
using BotSharp.Abstraction.Functions.Models;
45
using BotSharp.Abstraction.Repositories;
@@ -9,56 +10,54 @@
910
using System.Text;
1011
using System.Threading.Tasks;
1112

12-
namespace BotSharp.Plugin.EmailHandler.Hooks
13+
namespace BotSharp.Plugin.EmailHandler.Hooks;
14+
15+
public class EmailHandlerHook : AgentHookBase
1316
{
14-
public class EmailHandlerHook : AgentHookBase
15-
{
16-
private static string UTILITY_ASSISTANT = Guid.Empty.ToString();
17-
private static string FUNCTION_NAME = "handle_email_request";
17+
private static string FUNCTION_NAME = "handle_email_request";
1818

19-
public override string SelfId => string.Empty;
19+
public override string SelfId => string.Empty;
2020

21-
public EmailHandlerHook(IServiceProvider services, AgentSettings settings)
22-
: base(services, settings)
23-
{
24-
}
25-
public override void OnAgentLoaded(Agent agent)
26-
{
27-
var conv = _services.GetRequiredService<IConversationService>();
28-
var isConvMode = conv.IsConversationMode();
29-
var isEnabled = !agent.Utilities.IsNullOrEmpty() && agent.Utilities.Contains(Utility.EmailHandler);
21+
public EmailHandlerHook(IServiceProvider services, AgentSettings settings)
22+
: base(services, settings)
23+
{
24+
}
25+
public override void OnAgentLoaded(Agent agent)
26+
{
27+
var conv = _services.GetRequiredService<IConversationService>();
28+
var isConvMode = conv.IsConversationMode();
29+
var isEnabled = !agent.Utilities.IsNullOrEmpty() && agent.Utilities.Contains(Utility.EmailHandler);
3030

31-
if (isConvMode && isEnabled)
31+
if (isConvMode && isEnabled)
32+
{
33+
var (prompt, fn) = GetPromptAndFunction();
34+
if (fn != null)
3235
{
33-
var (prompt, fn) = GetPromptAndFunction();
34-
if (fn != null)
36+
if (!string.IsNullOrWhiteSpace(prompt))
3537
{
36-
if (!string.IsNullOrWhiteSpace(prompt))
37-
{
38-
agent.Instruction += $"\r\n\r\n{prompt}\r\n\r\n";
39-
}
38+
agent.Instruction += $"\r\n\r\n{prompt}\r\n\r\n";
39+
}
4040

41-
if (agent.Functions == null)
42-
{
43-
agent.Functions = new List<FunctionDef> { fn };
44-
}
45-
else
46-
{
47-
agent.Functions.Add(fn);
48-
}
41+
if (agent.Functions == null)
42+
{
43+
agent.Functions = new List<FunctionDef> { fn };
44+
}
45+
else
46+
{
47+
agent.Functions.Add(fn);
4948
}
5049
}
51-
52-
base.OnAgentLoaded(agent);
5350
}
5451

55-
private (string, FunctionDef?) GetPromptAndFunction()
56-
{
57-
var db = _services.GetRequiredService<IBotSharpRepository>();
58-
var agent = db.GetAgent(UTILITY_ASSISTANT);
59-
var prompt = agent?.Templates?.FirstOrDefault(x => x.Name.IsEqualTo($"{FUNCTION_NAME}.fn"))?.Content ?? string.Empty;
60-
var loadAttachmentFn = agent?.Functions?.FirstOrDefault(x => x.Name.IsEqualTo(FUNCTION_NAME));
61-
return (prompt, loadAttachmentFn);
62-
}
52+
base.OnAgentLoaded(agent);
53+
}
54+
55+
private (string, FunctionDef?) GetPromptAndFunction()
56+
{
57+
var db = _services.GetRequiredService<IBotSharpRepository>();
58+
var agent = db.GetAgent(BuiltInAgentId.UtilityAssistant);
59+
var prompt = agent?.Templates?.FirstOrDefault(x => x.Name.IsEqualTo($"{FUNCTION_NAME}.fn"))?.Content ?? string.Empty;
60+
var loadAttachmentFn = agent?.Functions?.FirstOrDefault(x => x.Name.IsEqualTo(FUNCTION_NAME));
61+
return (prompt, loadAttachmentFn);
6362
}
6463
}
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)