Skip to content

Commit 7c79bc7

Browse files
author
Jicheng Lu
committed
refine code
1 parent db08be2 commit 7c79bc7

File tree

8 files changed

+50
-25
lines changed

8 files changed

+50
-25
lines changed

src/Infrastructure/BotSharp.Abstraction/Agents/IAgentService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public interface IAgentService
1818
/// </summary>
1919
/// <param name="id"></param>
2020
/// <returns></returns>
21-
Task<Agent> LoadAgent(string id);
21+
Task<Agent> LoadAgent(string id, bool loadUtility = true);
2222

2323
/// <summary>
2424
/// Inherit from an agent

src/Infrastructure/BotSharp.Abstraction/Agents/Models/Agent.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,12 @@ public class Agent
118118
[JsonIgnore]
119119
public Dictionary<string, object> TemplateDict { get; set; } = new();
120120

121+
[JsonIgnore]
122+
public List<FunctionDef> SecondaryFunctions { get; set; } = [];
123+
124+
[JsonIgnore]
125+
public List<string> SecondaryInstructions { get; set; } = [];
126+
121127
public override string ToString()
122128
=> $"{Name} {Id}";
123129

src/Infrastructure/BotSharp.Core/Agents/Hooks/BasicAgentHook.cs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ public class BasicAgentHook : AgentHookBase
44
{
55
public override string SelfId => string.Empty;
66

7+
private const string UTIL_PREFIX = "util-";
8+
79
public BasicAgentHook(IServiceProvider services, AgentSettings settings)
810
: base(services, settings)
911
{
@@ -17,22 +19,23 @@ public override void OnAgentUtilityLoaded(Agent agent)
1719
var isConvMode = conv.IsConversationMode();
1820
if (!isConvMode) return;
1921

20-
agent.Functions ??= [];
22+
agent.SecondaryFunctions ??= [];
23+
agent.SecondaryInstructions ??= [];
2124
agent.Utilities ??= [];
2225

2326
var (functions, templates) = GetUtilityContent(agent);
2427

2528
foreach (var fn in functions)
2629
{
27-
if (!agent.Functions.Any(x => x.Name.Equals(fn.Name, StringComparison.OrdinalIgnoreCase)))
30+
if (!agent.SecondaryFunctions.Any(x => x.Name.Equals(fn.Name, StringComparison.OrdinalIgnoreCase)))
2831
{
29-
agent.Functions.Add(fn);
32+
agent.SecondaryFunctions.Add(fn);
3033
}
3134
}
3235

3336
foreach (var prompt in templates)
3437
{
35-
agent.Instruction += $"\r\n\r\n{prompt}\r\n\r\n";
38+
agent.SecondaryInstructions.Add(prompt);
3639
}
3740
}
3841

@@ -67,14 +70,13 @@ public override void OnAgentUtilityLoaded(Agent agent)
6770
return ([], []);
6871
}
6972

70-
var prefix = "util-";
7173
utilities = utilities?.Where(x => !string.IsNullOrEmpty(x.Name) && !x.Disabled)?.ToList() ?? [];
7274
var functionNames = utilities.SelectMany(x => x.Functions)
73-
.Where(x => !string.IsNullOrEmpty(x.Name) && x.Name.StartsWith(prefix))
75+
.Where(x => !string.IsNullOrEmpty(x.Name) && x.Name.StartsWith(UTIL_PREFIX))
7476
.Select(x => x.Name)
7577
.Distinct().ToList();
7678
var templateNames = utilities.SelectMany(x => x.Templates)
77-
.Where(x => !string.IsNullOrEmpty(x.Name) && x.Name.StartsWith(prefix))
79+
.Where(x => !string.IsNullOrEmpty(x.Name) && x.Name.StartsWith(UTIL_PREFIX))
7880
.Select(x => x.Name)
7981
.Distinct().ToList();
8082

src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.LoadAgent.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public partial class AgentService
88
public static ConcurrentDictionary<string, Dictionary<string, string>> AgentParameterTypes = new();
99

1010
[MemoryCache(10 * 60, perInstanceCache: true)]
11-
public async Task<Agent> LoadAgent(string id)
11+
public async Task<Agent> LoadAgent(string id, bool loadUtility = true)
1212
{
1313
if (string.IsNullOrEmpty(id) || id == Guid.Empty.ToString())
1414
{
@@ -67,7 +67,11 @@ public async Task<Agent> LoadAgent(string id)
6767
hook.OnSamplesLoaded(agent.Samples);
6868
}
6969

70-
hook.OnAgentUtilityLoaded(agent);
70+
if (loadUtility)
71+
{
72+
hook.OnAgentUtilityLoaded(agent);
73+
}
74+
7175
hook.OnAgentLoaded(agent);
7276
}
7377

src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.Rendering.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,17 @@ public string RenderedInstruction(Agent agent)
1111
var render = _services.GetRequiredService<ITemplateRender>();
1212
var conv = _services.GetRequiredService<IConversationService>();
1313

14+
// merge instructions
15+
var texts = new List<string> { agent.Instruction };
16+
texts.AddRange(agent.SecondaryInstructions ?? []);
17+
1418
// update states
1519
foreach (var t in conv.States.GetStates())
1620
{
1721
agent.TemplateDict[t.Key] = t.Value;
1822
}
1923

20-
var res = render.Render(agent.Instruction, agent.TemplateDict);
24+
var res = render.Render(string.Join("\r\n", texts), agent.TemplateDict);
2125
return res;
2226
}
2327

src/Plugins/BotSharp.Plugin.FileHandler/Functions/ReadImageFn.cs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,20 @@ public async Task<bool> Execute(RoleDialogModel message)
2424

2525
var wholeDialogs = conv.GetDialogHistory();
2626
var dialogs = AssembleFiles(conv.ConversationId, args?.ImageUrls, wholeDialogs);
27-
var agentId = !string.IsNullOrWhiteSpace(message.CurrentAgentId) ? message.CurrentAgentId : BuiltInAgentId.UtilityAssistant;
28-
var agent = await agentService.LoadAgent(agentId);
29-
var fileAgent = new Agent
27+
var agent = new Agent
3028
{
31-
Id = agent?.Id ?? Guid.Empty.ToString(),
32-
Name = agent?.Name ?? "Unkown",
29+
Id = BuiltInAgentId.UtilityAssistant,
30+
Name = "Utility Agent",
3331
Instruction = !string.IsNullOrWhiteSpace(args?.UserRequest) ? args.UserRequest : "Please describe the image(s).",
3432
TemplateDict = new Dictionary<string, object>()
3533
};
3634

37-
var response = await GetChatCompletion(fileAgent, dialogs);
35+
if (!string.IsNullOrEmpty(message.CurrentAgentId))
36+
{
37+
agent = await agentService.LoadAgent(message.CurrentAgentId, loadUtility: false);
38+
}
39+
40+
var response = await GetChatCompletion(agent, dialogs);
3841
message.Content = response;
3942
return true;
4043
}

src/Plugins/BotSharp.Plugin.OpenAI/Providers/Chat/ChatCompletionProvider.cs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
using BotSharp.Abstraction.Files.Utilities;
2+
using BotSharp.Abstraction.Templating;
23
using OpenAI.Chat;
4+
using static System.Net.Mime.MediaTypeNames;
35

46
namespace BotSharp.Plugin.OpenAI.Providers.Chat;
57

@@ -208,7 +210,9 @@ public async Task<bool> GetChatCompletionsStreamingAsync(Agent agent, List<RoleD
208210
MaxOutputTokenCount = maxTokens
209211
};
210212

211-
foreach (var function in agent.Functions)
213+
214+
var functions = agent.Functions.Concat(agent.SecondaryFunctions ?? []);
215+
foreach (var function in functions)
212216
{
213217
if (!agentService.RenderFunction(agent, function)) continue;
214218

@@ -220,10 +224,10 @@ public async Task<bool> GetChatCompletionsStreamingAsync(Agent agent, List<RoleD
220224
functionParameters: BinaryData.FromObjectAsJson(property)));
221225
}
222226

223-
if (!string.IsNullOrEmpty(agent.Instruction))
227+
if (!string.IsNullOrEmpty(agent.Instruction) || !agent.SecondaryInstructions.IsNullOrEmpty())
224228
{
225-
var instruction = agentService.RenderedInstruction(agent);
226-
messages.Add(new SystemChatMessage(instruction));
229+
var text = agentService.RenderedInstruction(agent);
230+
messages.Add(new SystemChatMessage(text));
227231
}
228232

229233
if (!string.IsNullOrEmpty(agent.Knowledges))

src/Plugins/BotSharp.Plugin.OpenAI/Providers/ProviderHelper.cs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@ public static OpenAIClient GetClient(string provider, string model, IServiceProv
99
{
1010
var settingsService = services.GetRequiredService<ILlmProviderService>();
1111
var settings = settingsService.GetSetting(provider, model);
12-
var options = string.IsNullOrEmpty(settings.Endpoint)
13-
? null
14-
: new OpenAIClientOptions { Endpoint = new Uri(settings.Endpoint) };
15-
return new OpenAIClient(new ApiKeyCredential(settings.ApiKey), options);
12+
//var options = string.IsNullOrEmpty(settings.Endpoint)
13+
// ? null
14+
// : new OpenAIClientOptions { Endpoint = new Uri(settings.Endpoint) };
15+
//return new OpenAIClient(new ApiKeyCredential(settings.ApiKey), options);
16+
var client = new OpenAIClient(new ApiKeyCredential(settings.ApiKey));
17+
return client;
1618
}
1719

1820
public static List<RoleDialogModel> GetChatSamples(List<string> lines)

0 commit comments

Comments
 (0)