Skip to content

Commit 12a706f

Browse files
authored
Merge pull request #820 from hchen2020/master
X-Twilio-BotSharp
2 parents 7b2d73c + 15363f4 commit 12a706f

File tree

8 files changed

+99
-15
lines changed

8 files changed

+99
-15
lines changed

src/Infrastructure/BotSharp.Abstraction/Conversations/Enums/ConversationChannel.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ public class ConversationChannel
88
public const string Messenger = "messenger";
99
public const string Email = "email";
1010
public const string Cron = "cron";
11+
public const string Database = "database";
1112
}
Lines changed: 65 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,85 @@
1+
using BotSharp.Abstraction.Conversations;
2+
using BotSharp.Abstraction.Conversations.Enums;
3+
using BotSharp.Abstraction.Models;
4+
using BotSharp.Abstraction.Repositories.Filters;
5+
using BotSharp.Abstraction.Routing;
6+
using BotSharp.Abstraction.Utilities;
17
using BotSharp.Core.Rules.Triggers;
8+
using Microsoft.Extensions.Logging;
9+
using System.Data;
210

311
namespace BotSharp.Core.Rules.Engines;
412

513
public class RuleEngine : IRuleEngine
614
{
715
private readonly IServiceProvider _services;
8-
public RuleEngine(IServiceProvider services)
16+
private readonly ILogger _logger;
17+
18+
public RuleEngine(IServiceProvider services, ILogger<RuleEngine> logger)
919
{
1020
_services = services;
21+
_logger = logger;
1122
}
1223

1324
public async Task Triggered(IRuleTrigger trigger, string data)
1425
{
1526
// Pull all user defined rules
16-
27+
var agentService = _services.GetRequiredService<IAgentService>();
28+
var agents = await agentService.GetAgents(new AgentFilter
29+
{
30+
Pager = new Pagination
31+
{
32+
Size = 1000
33+
}
34+
});
35+
36+
var preFilteredAgents = agents.Items.Where(x =>
37+
x.Rules.Exists(r => r.TriggerName == trigger.Name &&
38+
!x.Disabled)).ToList();
39+
40+
// Trigger the agents
1741
var instructService = _services.GetRequiredService<IInstructService>();
42+
var convService = _services.GetRequiredService<IConversationService>();
43+
44+
foreach (var agent in preFilteredAgents)
45+
{
46+
var conv = await convService.NewConversation(new Conversation
47+
{
48+
AgentId = agent.Id
49+
});
50+
51+
var message = new RoleDialogModel(AgentRole.User, data);
52+
53+
var states = new List<MessageState>
54+
{
55+
new("channel", ConversationChannel.Database),
56+
new("channel_id", trigger.EntityId)
57+
};
58+
convService.SetConversationId(conv.Id, states);
59+
60+
await convService.SendMessage(agent.Id,
61+
message,
62+
null,
63+
msg => Task.CompletedTask);
64+
65+
/*foreach (var rule in agent.Rules)
66+
{
67+
var userSay = $"===Input data with Before and After values===\r\n{data}\r\n\r\n===Trigger Criteria===\r\n{rule.Criteria}\r\n\r\nJust output 1 or 0 without explanation: ";
1868
19-
var userSay = $"===Input data===\r\n{data}\r\n\r\nWhen WO NTE is greater than 100, notify resident.";
69+
var result = await instructService.Execute(BuiltInAgentId.RulesInterpreter, new RoleDialogModel(AgentRole.User, userSay), "criteria_check", "#TEMPLATE#");
2070
21-
var result = await instructService.Execute(BuiltInAgentId.RulesInterpreter, new RoleDialogModel(AgentRole.User, data), "criteria_check", "#TEMPLATE#");
71+
// Check if meet the criteria
72+
if (result.Text == "1")
73+
{
74+
// Hit rule
75+
_logger.LogInformation($"Hit rule {rule.TriggerName} {rule.EntityType} {rule.EventName}, {data}");
2276
23-
string[] rules = [];
24-
// Check if meet the criteria
77+
await convService.SendMessage(agent.Id,
78+
new RoleDialogModel(AgentRole.User, $"The conversation was triggered by {rule.Criteria}"),
79+
null,
80+
msg => Task.CompletedTask);
81+
}
82+
}*/
83+
}
2584
}
2685
}

src/Infrastructure/BotSharp.Core.Rules/Triggers/IRuleTrigger.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ public interface IRuleTrigger
44
{
55
string Channel => throw new NotImplementedException("Please set the channel of trigger");
66

7-
string EventName { get; set; }
7+
string Name { get; set; }
8+
89
string EntityType { get; set; }
910

1011
string EntityId { get; set; }

src/Infrastructure/BotSharp.Core.Rules/data/agents/201e49a2-40b3-4ccd-b8cc-2476565a1b40/agent.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"id": "201e49a2-40b3-4ccd-b8cc-2476565a1b40",
33
"name": "Rules Agent",
4-
"description": "Utility assistant that can be used to complete many different tasks",
4+
"description": "Rules understands and converts user-defined rules into Triggers, Criterias and Actions",
55
"type": "static",
66
"createdDateTime": "2024-12-30T00:00:00Z",
77
"updatedDateTime": "2024-12-30T00:00:00Z",
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
You are a rule interpreter, analyze and respond according to the following steps:
22
1. Understand the rules customized by the user;
33
2. Determine whether the input data meets the user's action execution conditions;
4-
3. If it meets the conditions, output "true", otherwise output "false"
4+
3. If it meets the conditions, output number "1", otherwise output "0"

src/Plugins/BotSharp.Plugin.HttpHandler/Functions/HandleHttpRequestFn.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ namespace BotSharp.Plugin.HttpHandler.Functions;
99
public class HandleHttpRequestFn : IFunctionCallback
1010
{
1111
public string Name => "util-http-handle_http_request";
12-
public string Indication => "Handling http request";
12+
public string Indication => "Give me a second, I'm taking care of it!";
1313

1414
private readonly IServiceProvider _services;
1515
private readonly ILogger<HandleHttpRequestFn> _logger;

src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HandleOutboundPhoneCallFn.cs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using BotSharp.Abstraction.Files;
22
using BotSharp.Abstraction.Options;
3+
using BotSharp.Abstraction.Routing;
34
using BotSharp.Core.Infrastructures;
45
using BotSharp.Plugin.Twilio.Interfaces;
56
using BotSharp.Plugin.Twilio.Models;
@@ -49,10 +50,28 @@ public async Task<bool> Execute(RoleDialogModel message)
4950
return false;
5051
}
5152

53+
var convService = _services.GetRequiredService<IConversationService>();
54+
var convStorage = _services.GetRequiredService<IConversationStorage>();
55+
var routing = _services.GetRequiredService<IRoutingContext>();
5256
var fileStorage = _services.GetRequiredService<IFileStorageService>();
5357
var sessionManager = _services.GetRequiredService<ITwilioSessionManager>();
54-
var convService = _services.GetRequiredService<IConversationService>();
55-
var conversationId = convService.ConversationId;
58+
59+
// Fork conversation
60+
var entryAgentId = routing.EntryAgentId;
61+
var newConv = await convService.NewConversation(new Abstraction.Conversations.Models.Conversation
62+
{
63+
AgentId = entryAgentId,
64+
Channel = ConversationChannel.Phone
65+
});
66+
var conversationId = newConv.Id;
67+
convStorage.Append(conversationId, new RoleDialogModel(AgentRole.User, "Hi, I'm calling to check my work order quote status, please help me locate my work order number and let me know what to do next.")
68+
{
69+
CurrentAgentId = entryAgentId
70+
});
71+
convStorage.Append(conversationId, new RoleDialogModel(AgentRole.Assistant, args.InitialMessage)
72+
{
73+
CurrentAgentId = entryAgentId
74+
});
5675

5776
// Generate audio
5877
var completion = CompletionProvider.GetAudioCompletion(_services, "openai", "tts-1");
@@ -72,7 +91,7 @@ public async Task<bool> Execute(RoleDialogModel message)
7291
to: new PhoneNumber(args.PhoneNumber),
7392
from: new PhoneNumber(_twilioSetting.PhoneNumber));
7493

75-
message.Content = $"The generated phone message: {args.InitialMessage}" ?? message.Content;
94+
message.Content = $"The generated phone message: {args.InitialMessage}. \r\n[Conversation ID: {conversationId}]" ?? message.Content;
7695
message.StopCompletion = true;
7796
return true;
7897
}

src/Plugins/BotSharp.Plugin.Twilio/Services/TwilioMessageQueueService.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ private async Task ProcessUserMessageAsync(CallerMessage message)
6565
var httpContext = sp.GetRequiredService<IHttpContextAccessor>();
6666
httpContext.HttpContext = new DefaultHttpContext();
6767
httpContext.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity());
68+
httpContext.HttpContext.Request.Headers["X-Twilio-BotSharp"] = "LOST";
6869

6970
AssistantMessage reply = null;
7071
var inputMsg = new RoleDialogModel(AgentRole.User, message.Content);
@@ -75,8 +76,11 @@ private async Task ProcessUserMessageAsync(CallerMessage message)
7576
var progressService = sp.GetRequiredService<IConversationProgressService>();
7677
InitProgressService(message, sessionManager, progressService);
7778
InitConversation(message, inputMsg, conv, routing);
78-
79-
var result = await conv.SendMessage(config.AgentId,
79+
80+
var conversation = await conv.GetConversation(message.ConversationId);
81+
var agentId = string.IsNullOrWhiteSpace(conversation.AgentId) ? config.AgentId : conversation.AgentId;
82+
83+
var result = await conv.SendMessage(agentId,
8084
inputMsg,
8185
replyMessage: BuildPostbackMessageModel(conv, message),
8286
async msg =>

0 commit comments

Comments
 (0)