-
-
Notifications
You must be signed in to change notification settings - Fork 541
/
Copy pathAgentService.RefreshAgents.cs
96 lines (84 loc) · 3.47 KB
/
AgentService.RefreshAgents.cs
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
using BotSharp.Abstraction.Repositories.Enums;
using System.IO;
namespace BotSharp.Core.Agents.Services;
public partial class AgentService
{
public async Task<string> RefreshAgents()
{
string refreshResult;
var dbSettings = _services.GetRequiredService<BotSharpDatabaseSettings>();
if (dbSettings.Default == RepositoryEnum.FileRepository)
{
refreshResult = $"Invalid database repository setting: {dbSettings.Default}";
_logger.LogWarning(refreshResult);
return refreshResult;
}
var userIdentity = _services.GetRequiredService<IUserIdentity>();
var userService = _services.GetRequiredService<IUserService>();
var (isValid, _) = await userService.IsAdminUser(userIdentity.Id);
if (!isValid)
{
return "Unauthorized user.";
}
var agentDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
dbSettings.FileRepository,
_agentSettings.DataDir);
if (!Directory.Exists(agentDir))
{
refreshResult = $"Cannot find the directory: {agentDir}";
return refreshResult;
}
var refreshedAgents = new List<string>();
foreach (var dir in Directory.GetDirectories(agentDir))
{
try
{
var agentJson = File.ReadAllText(Path.Combine(dir, "agent.json"));
var agent = JsonSerializer.Deserialize<Agent>(agentJson, _options);
if (agent == null)
{
_logger.LogError($"Cannot find agent in file directory: {dir}");
continue;
}
var (defaultInstruction, channelInstructions) = GetInstructionsFromFile(dir);
var functions = GetFunctionsFromFile(dir);
var responses = GetResponsesFromFile(dir);
var templates = GetTemplatesFromFile(dir);
var links = GetLinksFromFile(dir);
var samples = GetSamplesFromFile(dir);
agent.SetInstruction(defaultInstruction)
.SetChannelInstructions(channelInstructions)
.SetTemplates(templates)
.SetLinks(links)
.SetFunctions(functions)
.SetResponses(responses)
.SetSamples(samples);
var tasks = GetTasksFromFile(dir);
var isAgentDeleted = _db.DeleteAgent(agent.Id);
if (isAgentDeleted)
{
await Task.Delay(100);
_db.BulkInsertAgents(new List<Agent> { agent });
_db.BulkInsertAgentTasks(tasks);
refreshedAgents.Add(agent.Name);
_logger.LogInformation($"Agent {agent.Name} has been migrated.");
}
}
catch (Exception ex)
{
_logger.LogError($"Failed to migrate agent in file directory: {dir}\r\nError: {ex.Message}");
}
}
if (!refreshedAgents.IsNullOrEmpty())
{
Utilities.ClearCache();
refreshResult = $"Agents are migrated!\r\n{string.Join("\r\n", refreshedAgents)}";
}
else
{
refreshResult = "No agent gets refreshed!";
}
_logger.LogInformation(refreshResult);
return refreshResult;
}
}