-
-
Notifications
You must be signed in to change notification settings - Fork 642
add criteria #1382
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
iceljc
wants to merge
3
commits into
SciSharp:master
Choose a base branch
from
iceljc:features/add-rule-criteria
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
add criteria #1382
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
src/Infrastructure/BotSharp.Abstraction/Coding/Options/CodeGenerationOptions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
src/Infrastructure/BotSharp.Abstraction/Rules/Constants/BuiltInRuleCriteria.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| namespace BotSharp.Abstraction.Rules.Constants; | ||
|
|
||
| /// <summary> | ||
| /// Built-in rule criteria types. Each value maps to an | ||
| /// <see cref="IRuleCriteriaEvaluator.Type"/> registered in DI. | ||
| /// Plugins may introduce additional string types. | ||
| /// </summary> | ||
| public static class BuiltInRuleCriteria | ||
| { | ||
| /// <summary> | ||
| /// Evaluate a code script (e.g. Python) that returns a boolean result. | ||
| /// </summary> | ||
| public const string Code = "code"; | ||
|
|
||
| /// <summary> | ||
| /// Ask an LLM whether the rule applies to the request. | ||
| /// </summary> | ||
| public const string Llm = "llm"; | ||
| } |
25 changes: 25 additions & 0 deletions
25
src/Infrastructure/BotSharp.Abstraction/Rules/IRuleCriteriaEvaluator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| using BotSharp.Abstraction.Rules.Models; | ||
|
|
||
| namespace BotSharp.Abstraction.Rules; | ||
|
|
||
| /// <summary> | ||
| /// Decides whether a rule should be executed for the current request. | ||
| /// Implementations are resolved by <see cref="Type"/> in the rule engine, | ||
| /// so new criteria mechanisms can be added without changing the engine. | ||
| /// </summary> | ||
| public interface IRuleCriteriaEvaluator | ||
| { | ||
| /// <summary> | ||
| /// The criteria type this evaluator handles | ||
| /// </summary> | ||
| string Type { get; } | ||
|
|
||
| /// <summary> | ||
| /// Evaluate the criteria for a single agent's rule. | ||
| /// </summary> | ||
| /// <param name="agent">The agent whose rule is being considered</param> | ||
| /// <param name="trigger">The rule trigger</param> | ||
| /// <param name="context">The per-request criteria context</param> | ||
| /// <returns>True if the rule should be executed for this request.</returns> | ||
| Task<bool> EvaluateAsync(Agent agent, IRuleTrigger trigger, RuleCriteriaContext context); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 23 additions & 0 deletions
23
src/Infrastructure/BotSharp.Abstraction/Rules/Models/RuleCriteriaContext.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| namespace BotSharp.Abstraction.Rules.Models; | ||
|
|
||
| /// <summary> | ||
| /// The per-request context passed to an <see cref="IRuleCriteriaEvaluator"/> | ||
| /// to decide whether a rule should be executed. | ||
| /// </summary> | ||
| public class RuleCriteriaContext | ||
| { | ||
| /// <summary> | ||
| /// The trigger message text. | ||
| /// </summary> | ||
| public string Text { get; set; } = string.Empty; | ||
|
|
||
| /// <summary> | ||
| /// The criteria options (evaluator type and its arguments). | ||
| /// </summary> | ||
| public CriteriaOptions Options { get; set; } = new(); | ||
|
|
||
| /// <summary> | ||
| /// The conversation states carried with the request. | ||
| /// </summary> | ||
| public IEnumerable<MessageState>? States { get; set; } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
125 changes: 125 additions & 0 deletions
125
src/Infrastructure/BotSharp.Core.Rules/Criteria/Code/CodeCriteriaEvaluator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| namespace BotSharp.Core.Rules.Criteria.Code; | ||
|
|
||
| /// <summary> | ||
| /// Evaluates rule trigger criteria by running an agent code script (e.g. Python) | ||
| /// that returns a boolean ("true"/"false") result. | ||
| /// </summary> | ||
| public class CodeCriteriaEvaluator : IRuleCriteriaEvaluator | ||
| { | ||
| private readonly IServiceProvider _services; | ||
| private readonly ILogger<CodeCriteriaEvaluator> _logger; | ||
| private readonly CodingSettings _codingSettings; | ||
|
|
||
| public CodeCriteriaEvaluator( | ||
| IServiceProvider services, | ||
| ILogger<CodeCriteriaEvaluator> logger, | ||
| CodingSettings codingSettings) | ||
| { | ||
| _services = services; | ||
| _logger = logger; | ||
| _codingSettings = codingSettings; | ||
| } | ||
|
|
||
| public string Type => BuiltInRuleCriteria.Code; | ||
|
|
||
| public async Task<bool> EvaluateAsync(Agent agent, IRuleTrigger trigger, RuleCriteriaContext context) | ||
| { | ||
| var settings = context.Options.GetData<CodeCriteriaSettings>() ?? new(); | ||
| var provider = settings.CodeProcessor ?? BuiltInCodeProcessor.PyInterpreter; | ||
| var processor = _services.GetServices<ICodeProcessor>().FirstOrDefault(x => x.Provider.IsEqualTo(provider)); | ||
| if (processor == null) | ||
| { | ||
| _logger.LogWarning($"Unable to find code processor: {provider}."); | ||
| return true; | ||
| } | ||
|
|
||
| var agentService = _services.GetRequiredService<IAgentService>(); | ||
| var scriptName = settings.CodeScriptName ?? $"{trigger.Name}_rule.py"; | ||
| var codeScript = await agentService.GetAgentCodeScript(agent.Id, scriptName, scriptType: AgentCodeScriptType.Src); | ||
|
|
||
| var msg = $"rule trigger ({trigger.Name}) code script ({scriptName}) in agent ({agent.Name}) => args: {settings.ArgumentContent?.RootElement.GetRawText()}."; | ||
|
|
||
| if (codeScript == null || string.IsNullOrWhiteSpace(codeScript.Content)) | ||
| { | ||
| _logger.LogWarning($"Unable to find {msg}."); | ||
| return true; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| var hooks = _services.GetHooks<IInstructHook>(agent.Id); | ||
|
|
||
| var arguments = BuildArguments(settings.ArgumentName, settings.ArgumentContent); | ||
| var codeContext = new CodeExecutionContext | ||
| { | ||
| CodeScript = codeScript, | ||
| Arguments = arguments | ||
| }; | ||
|
|
||
| foreach (var hook in hooks) | ||
| { | ||
| await hook.BeforeCodeExecution(agent, codeContext); | ||
| } | ||
|
|
||
| var (useLock, useProcess, timeoutSeconds) = CodingUtil.GetCodeExecutionConfig(_codingSettings); | ||
| using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds)); | ||
| var response = processor.Run(codeScript.Content, options: new() | ||
| { | ||
| ScriptName = scriptName, | ||
| Arguments = arguments, | ||
| UseLock = useLock, | ||
| UseProcess = useProcess | ||
| }, cancellationToken: cts.Token); | ||
|
|
||
| var codeResponse = new CodeExecutionResponseModel | ||
| { | ||
| CodeProcessor = processor.Provider, | ||
| CodeScript = codeScript, | ||
| Arguments = arguments.DistinctBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value ?? string.Empty), | ||
| ExecutionResult = response | ||
| }; | ||
|
|
||
| foreach (var hook in hooks) | ||
| { | ||
| await hook.AfterCodeExecution(agent, codeContext, codeResponse); | ||
| } | ||
|
|
||
| if (response == null || !response.Success) | ||
| { | ||
| _logger.LogWarning($"Failed to handle {msg}"); | ||
| return false; | ||
| } | ||
|
|
||
| bool result; | ||
| LogLevel logLevel; | ||
| if (response.Result.IsEqualTo("true")) | ||
| { | ||
| logLevel = LogLevel.Information; | ||
| result = true; | ||
| } | ||
| else | ||
| { | ||
| logLevel = LogLevel.Warning; | ||
| result = false; | ||
| } | ||
|
|
||
| _logger.Log(logLevel, $"Code script execution result ({response}) from {msg}"); | ||
| return result; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogError(ex, $"Error when handling {msg}"); | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| private List<KeyValue> BuildArguments(string? name, JsonDocument? args) | ||
| { | ||
| var keyValues = new List<KeyValue>(); | ||
| if (args != null) | ||
| { | ||
| keyValues.Add(new KeyValue(name ?? "trigger_args", args.RootElement.GetRawText())); | ||
| } | ||
| return keyValues; | ||
| } | ||
| } | ||
34 changes: 34 additions & 0 deletions
34
src/Infrastructure/BotSharp.Core.Rules/Criteria/Code/CodeCriteriaSettings.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| using System.Text.Json.Serialization; | ||
|
|
||
| namespace BotSharp.Core.Rules.Criteria.Code; | ||
|
|
||
| /// <summary> | ||
| /// Settings for <see cref="CodeCriteriaEvaluator"/>, parsed from | ||
| /// <c>CriteriaOptions.Data</c>. | ||
| /// </summary> | ||
| public class CodeCriteriaSettings | ||
| { | ||
| /// <summary> | ||
| /// Code processor provider (defaults to the Python interpreter). | ||
| /// </summary> | ||
| [JsonPropertyName("code_processor")] | ||
| public string? CodeProcessor { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Code script name. | ||
| /// </summary> | ||
| [JsonPropertyName("code_script_name")] | ||
| public string? CodeScriptName { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Argument name as an input key to the code script. | ||
| /// </summary> | ||
| [JsonPropertyName("argument_name")] | ||
| public string? ArgumentName { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Json arguments as an input value to the code script. | ||
| /// </summary> | ||
| [JsonPropertyName("argument_content")] | ||
| public JsonDocument? ArgumentContent { get; set; } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
1. codecriteriaevaluator fails open
📘 Rule violation☼ ReliabilityAgent Prompt
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools