Merge branch 'master' of https://github.com/SciSharp/BotSharp into features/refine-knowledge-base

This commit is contained in:
Jicheng Lu 2024-08-07 09:57:37 -05:00
commit 58cf4494f6
2 changed files with 65 additions and 1 deletions

View file

@ -1,7 +1,12 @@
using BotSharp.Abstraction.Routing.Models;
using System.Collections.Concurrent;
namespace BotSharp.Core.Agents.Services;
public partial class AgentService
{
public static ConcurrentDictionary<string, Dictionary<string,string>> AgentParameterTypes = new();
[MemoryCache(10 * 60, perInstanceCache: true)]
public async Task<Agent> LoadAgent(string id)
{
@ -49,6 +54,7 @@ public partial class AgentService
agent.Instruction = inheritedAgent.Instruction;
}
}
AddOrUpdateParameters(agent);
agent.TemplateDict = new Dictionary<string, object>();
@ -96,4 +102,43 @@ public partial class AgentService
dict[t.Key] = t.Value;
}
}
private void AddOrUpdateParameters(Agent agent)
{
var agentId = agent.Id ?? agent.Name;
if (AgentParameterTypes.ContainsKey(agentId)) return;
AddOrUpdateRoutesParameters(agentId, agent.RoutingRules);
AddOrUpdateFunctionsParameters(agentId, agent.Functions);
}
private void AddOrUpdateRoutesParameters(string agentId, List<RoutingRule> routingRules)
{
if(!AgentParameterTypes.TryGetValue(agentId, out var parameterTypes)) parameterTypes = new();
foreach (var rule in routingRules.Where(x => x.Required))
{
if (string.IsNullOrEmpty(rule.FieldType)) continue;
parameterTypes.TryAdd(rule.Field, rule.FieldType);
}
AgentParameterTypes.TryAdd(agentId, parameterTypes);
}
private void AddOrUpdateFunctionsParameters(string agentId, List<FunctionDef> functions)
{
if (!AgentParameterTypes.TryGetValue(agentId, out var parameterTypes)) parameterTypes = new();
var parameters = functions.Select(p => p.Parameters);
foreach (var param in parameters)
{
foreach (JsonProperty prop in param.Properties.RootElement.EnumerateObject())
{
var name = prop.Name;
var node = prop.Value;
if (node.TryGetProperty("type", out var type))
{
parameterTypes.TryAdd(name, type.GetString());
}
}
}
AgentParameterTypes.TryAdd(agentId, parameterTypes);
}
}

View file

@ -360,9 +360,28 @@ public class ConversationStateService : IConversationStateService, IDisposable
stateValue = stateValue?.ToLower();
}
SetState(property.Name, stateValue, source: StateSource.Application);
if (CheckArgType(property.Name, stateValue))
{
SetState(property.Name, stateValue, source: StateSource.Application);
}
}
}
}
}
private bool CheckArgType(string name, string value)
{
var agentTypes = AgentService.AgentParameterTypes.SelectMany(p => p.Value).ToList();
var filed = agentTypes.FirstOrDefault(t => t.Key == name);
if (filed.Key != null)
{
return filed.Value switch
{
"boolean" => bool.TryParse(value, out _),
"number" => long.TryParse(value, out _),
_ => true,
};
}
return true;
}
}