-
-
Notifications
You must be signed in to change notification settings - Fork 622
Expand file tree
/
Copy pathConversationService.SendMessage.cs
More file actions
181 lines (150 loc) · 6.82 KB
/
ConversationService.SendMessage.cs
File metadata and controls
181 lines (150 loc) · 6.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
using BotSharp.Abstraction.Infrastructures.Enums;
using BotSharp.Abstraction.Messaging;
using BotSharp.Abstraction.Messaging.Models.RichContent;
using BotSharp.Abstraction.Routing.Settings;
namespace BotSharp.Core.Conversations.Services;
public partial class ConversationService
{
public async Task<bool> SendMessage(string agentId,
RoleDialogModel message,
PostbackMessageModel? replyMessage,
Func<RoleDialogModel, Task> onMessageReceived)
{
var conversation = await GetConversationRecordOrCreateNew(agentId);
var agentService = _services.GetRequiredService<IAgentService>();
Agent agent = await agentService.LoadAgent(agentId);
var content = $"Received [{agent.Name}] {message.Role}: {message.Content}";
_logger.LogInformation(content);
message.CurrentAgentId = agent.Id;
if (string.IsNullOrEmpty(message.SenderId))
{
message.SenderId = _user.Id;
}
var conv = _services.GetRequiredService<IConversationService>();
var dialogs = await conv.GetDialogHistory();
var statistics = _services.GetRequiredService<ITokenStatistics>();
RoleDialogModel response = message;
bool stopCompletion = false;
// Enqueue receiving agent first in case it stop completion by OnMessageReceived
var routing = _services.GetRequiredService<IRoutingService>();
routing.Context.SetMessageId(_conversationId, message.MessageId);
// Save payload in order to assign the payload before hook is invoked
if (replyMessage != null && !string.IsNullOrEmpty(replyMessage.Payload))
{
message.Payload = replyMessage.Payload;
}
var hooks = _services.GetHooksOrderByPriority<IConversationHook>(message.CurrentAgentId);
foreach (var hook in hooks)
{
hook.SetAgent(agent)
.SetConversation(conversation);
if (replyMessage == null || string.IsNullOrEmpty(replyMessage.FunctionName))
{
await hook.OnMessageReceived(message);
}
else
{
await hook.OnPostbackMessageReceived(message, replyMessage);
}
// Interrupted by hook
if (message.StopCompletion)
{
stopCompletion = true;
await routing.Context.Pop();
break;
}
}
if (!stopCompletion)
{
// Routing with reasoning
var settings = _services.GetRequiredService<RoutingSettings>();
// reload agent in case it has been changed by hook
if (message.CurrentAgentId != agent.Id)
{
agent = await agentService.LoadAgent(message.CurrentAgentId);
}
if (agent.Type == AgentType.Routing)
{
await routing.Context.Push(agent.Id, reason: "request started", updateLazyRouting: false);
// Check the routing mode
var states = _services.GetRequiredService<IConversationStateService>();
var routingMode = states.GetState(StateConst.ROUTING_MODE, agent.Mode ?? RoutingMode.Eager);
var lazyRoutingAgentId = states.GetState(StateConst.LAZY_ROUTING_AGENT_ID);
if (routingMode == RoutingMode.Lazy && !string.IsNullOrEmpty(lazyRoutingAgentId))
{
message.CurrentAgentId = lazyRoutingAgentId;
agent = await agentService.LoadAgent(message.CurrentAgentId);
await routing.Context.Push(message.CurrentAgentId, reason: "lazy routing", updateLazyRouting: false);
response = await routing.InstructDirect(agent, message, dialogs);
}
else
{
response = await routing.InstructLoop(agent, message, dialogs);
}
}
else
{
response = await routing.InstructDirect(agent, message, dialogs);
}
routing.Context.ResetRecursiveCounter();
}
await HandleAssistantMessage(response, onMessageReceived);
statistics.PrintStatistics();
return true;
}
private async Task HandleAssistantMessage(RoleDialogModel response, Func<RoleDialogModel, Task> onResponseReceived)
{
var agentService = _services.GetRequiredService<IAgentService>();
var agent = await agentService.GetAgent(response.CurrentAgentId);
var agentName = agent.Name;
// Send message always in assistant role
response.Role = AgentRole.Assistant;
var text = $"Sending [{agentName}] {response.Role}: {response.Content}";
#if DEBUG
Console.WriteLine(text);
#else
_logger.LogInformation(text);
#endif
// Process rich content
if (response.RichContent != null &&
response.RichContent is RichContent<IRichMessage> template &&
string.IsNullOrEmpty(template.Message.Text))
{
template.Message.Text = response.SecondaryContent ?? response.Content;
}
// Only read content from RichContent for UI rendering. When richContent is null, create a basic text message for richContent.
var state = _services.GetRequiredService<IConversationStateService>();
response.RichContent = response.RichContent ?? new RichContent<IRichMessage>
{
Recipient = new Recipient { Id = state.GetConversationId() },
Message = new TextMessage(response.SecondaryContent ?? response.Content)
};
// Use model refined response
if (string.IsNullOrEmpty(response.RichContent.Message.Text))
{
response.RichContent.Message.Text = response.Content;
}
// Patch return function name
if (response.PostbackFunctionName != null)
{
response.FunctionName = response.PostbackFunctionName;
}
if (response.Instruction != null)
{
var conversation = _services.GetRequiredService<IConversationService>();
await conversation.UpdateConversationTitle(_conversationId, response.Instruction.NextActionReason);
// Emit conversation ending hook
if (response.Instruction.ConversationEnd)
{
await HookEmitter.Emit<IConversationHook>(_services, async hook => await hook.OnConversationEnding(response),
response.CurrentAgentId);
response.FunctionName = "conversation_end";
}
}
await HookEmitter.Emit<IConversationHook>(_services, async hook => await hook.OnResponseGenerated(response),
response.CurrentAgentId);
await onResponseReceived(response);
// Add to dialog history
await _storage.Append(_conversationId, response);
}
}