Skip to content

add http request hook #815

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

Merged
merged 2 commits into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public enum AgentField
LlmConfig,
Utility,
KnowledgeBase,
EventRule,
Rule,
MaxMessageCount
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace BotSharp.Abstraction.Agents;

public interface IAgentRuleHook
{
void AddRules(List<AgentRule> rules);
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public class Agent
/// <summary>
/// Agent rules
/// </summary>
public List<AgentEventRule> EventRules { get; set; } = new();
public List<AgentRule> Rules { get; set; } = new();

/// <summary>
/// Agent knowledge bases
Expand Down Expand Up @@ -159,7 +159,7 @@ public static Agent Clone(Agent agent)
MaxMessageCount = agent.MaxMessageCount,
Profiles = agent.Profiles,
RoutingRules = agent.RoutingRules,
EventRules = agent.EventRules,
Rules = agent.Rules,
LlmConfig = agent.LlmConfig,
KnowledgeBases = agent.KnowledgeBases,
CreatedDateTime = agent.CreatedDateTime,
Expand Down Expand Up @@ -275,9 +275,9 @@ public Agent SetRoutingRules(List<RoutingRule> rules)
return this;
}

public Agent SetEventRules(List<AgentEventRule> rules)
public Agent SetRules(List<AgentRule> rules)
{
EventRules = rules ?? [];
Rules = rules ?? [];
return this;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace BotSharp.Abstraction.Agents.Models;

public class AgentEventRule
public class AgentRule
{
public string Name { get; set; }
public bool Disabled { get; set; }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using System.Net.Http.Headers;

namespace BotSharp.Abstraction.Http;

public interface IHttpRequestHook
{
void OnAddHttpHeaders(HttpHeaders headers);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using BotSharp.Abstraction.Users.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace BotSharp.Abstraction.Users;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public async Task UpdateAgent(Agent agent, AgentField updateField)
record.Samples = agent.Samples ?? [];
record.Utilities = agent.Utilities ?? [];
record.KnowledgeBases = agent.KnowledgeBases ?? [];
record.EventRules = agent.EventRules ?? [];
record.Rules = agent.Rules ?? [];
if (agent.LlmConfig != null && !agent.LlmConfig.IsInherit)
{
record.LlmConfig = agent.LlmConfig;
Expand Down Expand Up @@ -105,7 +105,7 @@ public async Task<string> UpdateAgentFromFile(string id)
.SetSamples(foundAgent.Samples)
.SetUtilities(foundAgent.Utilities)
.SetKnowledgeBases(foundAgent.KnowledgeBases)
.SetEventRules(foundAgent.EventRules)
.SetRules(foundAgent.Rules)
.SetLlmConfig(foundAgent.LlmConfig);

_db.UpdateAgent(clonedAgent, AgentField.All);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ public void UpdateAgent(Agent agent, AgentField field)
case AgentField.KnowledgeBase:
UpdateAgentKnowledgeBases(agent.Id, agent.KnowledgeBases);
break;
case AgentField.EventRule:
UpdateAgentEventRules(agent.Id, agent.EventRules);
case AgentField.Rule:
UpdateAgentRules(agent.Id, agent.Rules);
break;
case AgentField.MaxMessageCount:
UpdateAgentMaxMessageCount(agent.Id, agent.MaxMessageCount);
Expand Down Expand Up @@ -187,14 +187,14 @@ private void UpdateAgentKnowledgeBases(string agentId, List<AgentKnowledgeBase>
File.WriteAllText(agentFile, json);
}

private void UpdateAgentEventRules(string agentId, List<AgentEventRule> rules)
private void UpdateAgentRules(string agentId, List<AgentRule> rules)
{
if (rules == null) return;

var (agent, agentFile) = GetAgentFromFile(agentId);
if (agent == null) return;

agent.EventRules = rules;
agent.Rules = rules;
agent.UpdatedDateTime = DateTime.UtcNow;
var json = JsonSerializer.Serialize(agent, _options);
File.WriteAllText(agentFile, json);
Expand Down Expand Up @@ -344,7 +344,7 @@ private void UpdateAgentAllFields(Agent inputAgent)
agent.Utilities = inputAgent.Utilities;
agent.KnowledgeBases = inputAgent.KnowledgeBases;
agent.RoutingRules = inputAgent.RoutingRules;
agent.EventRules = inputAgent.EventRules;
agent.Rules = inputAgent.Rules;
agent.LlmConfig = inputAgent.LlmConfig;
agent.MaxMessageCount = inputAgent.MaxMessageCount;
agent.UpdatedDateTime = DateTime.UtcNow;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@

<ItemGroup>
<ProjectReference Include="..\BotSharp.Core\BotSharp.Core.csproj" />
<ProjectReference Include="..\BotSharp.Core.Rules\BotSharp.Core.Rules.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using BotSharp.Abstraction.Agents.Models;
using BotSharp.Core.Infrastructures;
using BotSharp.Core.Rules.Hooks;

namespace BotSharp.OpenAPI.Controllers;

Expand Down Expand Up @@ -163,11 +161,11 @@ public IEnumerable<AgentUtility> GetAgentUtilityOptions()
return utilities.Where(x => !string.IsNullOrWhiteSpace(x.Name)).OrderBy(x => x.Name).ToList();
}

[HttpGet("/agent/event-rule/options")]
public IEnumerable<AgentEventRule> GetAgentEventRuleOptions()
[HttpGet("/agent/rule/options")]
public IEnumerable<AgentRule> GetAgentRuleOptions()
{
var rules = new List<AgentEventRule>();
var hooks = _services.GetServices<IEventRuleHook>();
var rules = new List<AgentRule>();
var hooks = _services.GetServices<IAgentRuleHook>();
foreach (var hook in hooks)
{
hook.AddRules(rules);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public class AgentCreationModel
public List<AgentUtility> Utilities { get; set; } = new();
public List<RoutingRuleUpdateModel> RoutingRules { get; set; } = new();
public List<AgentKnowledgeBase> KnowledgeBases { get; set; } = new();
public List<AgentEventRule> EventRules { get; set; } = new();
public List<AgentRule> Rules { get; set; } = new();
public AgentLlmConfig? LlmConfig { get; set; }

public Agent ToAgent()
Expand All @@ -79,7 +79,7 @@ public Agent ToAgent()
Profiles = Profiles,
LlmConfig = LlmConfig,
KnowledgeBases = KnowledgeBases,
EventRules = EventRules,
Rules = Rules,
RoutingRules = RoutingRules?.Select(x => RoutingRuleUpdateModel.ToDomainElement(x))?.ToList() ?? [],
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ public class AgentUpdateModel
[JsonPropertyName("routing_rules")]
public List<RoutingRuleUpdateModel>? RoutingRules { get; set; }

[JsonPropertyName("event_rules")]
public List<AgentEventRule>? EventRules { get; set; }
[JsonPropertyName("rules")]
public List<AgentRule>? Rules { get; set; }

[JsonPropertyName("llm_config")]
public AgentLlmConfig? LlmConfig { get; set; }
Expand All @@ -101,7 +101,7 @@ public Agent ToAgent()
Responses = Responses ?? [],
Utilities = Utilities ?? [],
KnowledgeBases = KnowledgeBases ?? [],
EventRules = EventRules ?? [],
Rules = Rules ?? [],
LlmConfig = LlmConfig
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ public class AgentViewModel
[JsonPropertyName("knowledge_bases")]
public List<AgentKnowledgeBase> KnowledgeBases { get; set; }

[JsonPropertyName("event_rules")]
public List<AgentEventRule> EventRules { get; set; }
[JsonPropertyName("rules")]
public List<AgentRule> Rules { get; set; }

[JsonPropertyName("is_public")]
public bool IsPublic { get; set; }
Expand Down Expand Up @@ -89,7 +89,7 @@ public static AgentViewModel FromAgent(Agent agent)
MaxMessageCount = agent.MaxMessageCount,
Profiles = agent.Profiles ?? [],
RoutingRules = agent.RoutingRules ?? [],
EventRules = agent.EventRules ?? [],
Rules = agent.Rules ?? [],
LlmConfig = agent.LlmConfig,
Plugin = agent.Plugin,
CreatedDateTime = agent.CreatedDateTime,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Net.Http;
using System.Net.Mime;
using BotSharp.Abstraction.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

Expand All @@ -13,7 +14,6 @@ public class HandleHttpRequestFn : IFunctionCallback
private readonly IServiceProvider _services;
private readonly ILogger<HandleHttpRequestFn> _logger;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IHttpContextAccessor _context;
private readonly BotSharpOptions _options;

public HandleHttpRequestFn(IServiceProvider services,
Expand All @@ -25,7 +25,6 @@ public HandleHttpRequestFn(IServiceProvider services,
_services = services;
_logger = logger;
_httpClientFactory = httpClientFactory;
_context = context;
_options = options;
}

Expand All @@ -46,7 +45,7 @@ public async Task<bool> Execute(RoleDialogModel message)
catch (Exception ex)
{
var msg = $"Fail when sending http request. Url: {url}, method: {method}, content: {content}";
_logger.LogWarning($"{msg}\n(Error: {ex.Message})");
_logger.LogError($"{msg}\n(Error: {ex.Message}\r\n{ex.InnerException})");
message.Content = msg;
return false;
}
Expand All @@ -57,7 +56,7 @@ public async Task<bool> Execute(RoleDialogModel message)
if (string.IsNullOrEmpty(url)) return null;

using var client = _httpClientFactory.CreateClient();
AddRequestHeaders(client);
PrepareRequestHeaders(client);

var (uri, request) = BuildHttpRequest(url, method, content);
var response = await client.SendAsync(request);
Expand All @@ -69,15 +68,12 @@ public async Task<bool> Execute(RoleDialogModel message)
return response;
}

private void AddRequestHeaders(HttpClient client)
private void PrepareRequestHeaders(HttpClient client)
{
client.DefaultRequestHeaders.Add("Authorization", $"{_context.HttpContext.Request.Headers["Authorization"]}");

var settings = _services.GetRequiredService<HttpHandlerSettings>();
var origin = !string.IsNullOrEmpty(settings.Origin) ? settings.Origin : $"{_context.HttpContext.Request.Headers["Origin"]}";
if (!string.IsNullOrEmpty(origin))
var hooks = _services.GetServices<IHttpRequestHook>();
foreach (var hook in hooks)
{
client.DefaultRequestHeaders.Add("Origin", origin);
hook.OnAddHttpHeaders(client.DefaultRequestHeaders);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using BotSharp.Abstraction.Http;
using Microsoft.AspNetCore.Http;
using System.Net.Http.Headers;

namespace BotSharp.Plugin.HttpHandler.Hooks;

public class BasicHttpRequestHook : IHttpRequestHook
{
private readonly IServiceProvider _services;
private readonly IHttpContextAccessor _context;

private const string AUTHORIZATION = "Authorization";
private const string ORIGIN = "Origin";

public BasicHttpRequestHook(
IServiceProvider services,
IHttpContextAccessor context)
{
_services = services;
_context = context;
}

public void OnAddHttpHeaders(HttpHeaders headers)
{
var settings = _services.GetRequiredService<HttpHandlerSettings>();

var auth = $"{_context.HttpContext.Request.Headers[AUTHORIZATION]}";
if (!string.IsNullOrEmpty(auth))
{
headers.Add(AUTHORIZATION, auth);
}

var origin = $"{_context.HttpContext.Request.Headers[ORIGIN]}";
origin = !string.IsNullOrEmpty(settings.Origin) ? settings.Origin : origin;
if (!string.IsNullOrEmpty(origin))
{
headers.Add(ORIGIN, origin);
}
}
}
2 changes: 2 additions & 0 deletions src/Plugins/BotSharp.Plugin.HttpHandler/HttpHandlerPlugin.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using BotSharp.Abstraction.Agents;
using BotSharp.Abstraction.Http;
using BotSharp.Abstraction.Settings;
using Microsoft.Extensions.Configuration;

Expand All @@ -21,5 +22,6 @@ public void RegisterDI(IServiceCollection services, IConfiguration config)
});

services.AddScoped<IAgentUtilityHook, HttpHandlerUtilityHook>();
services.AddScoped<IHttpRequestHook, BasicHttpRequestHook>();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class AgentDocument : MongoBase
public List<AgentKnowledgeBaseMongoElement> KnowledgeBases { get; set; }
public List<string> Profiles { get; set; }
public List<RoutingRuleMongoElement> RoutingRules { get; set; }
public List<AgentEventRuleMongoElement> EventRules { get; set; }
public List<AgentRuleMongoElement> Rules { get; set; }
public AgentLlmConfigMongoElement? LlmConfig { get; set; }

public DateTime CreatedTime { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

namespace BotSharp.Plugin.MongoStorage.Models;

public class AgentEventRuleMongoElement
public class AgentRuleMongoElement
{
public string Name { get; set; }
public bool Disabled { get; set; }
public string EventName { get; set; }
public string EntityType { get; set; }

public static AgentEventRuleMongoElement ToMongoElement(AgentEventRule rule)
public static AgentRuleMongoElement ToMongoElement(AgentRule rule)
{
return new AgentEventRuleMongoElement
return new AgentRuleMongoElement
{
Name = rule.Name,
Disabled = rule.Disabled,
Expand All @@ -20,9 +20,9 @@ public static AgentEventRuleMongoElement ToMongoElement(AgentEventRule rule)
};
}

public static AgentEventRule ToDomainElement(AgentEventRuleMongoElement rule)
public static AgentRule ToDomainElement(AgentRuleMongoElement rule)
{
return new AgentEventRule
return new AgentRule
{
Name = rule.Name,
Disabled = rule.Disabled,
Expand Down
Loading