Skip to content

Commit

Permalink
Merge pull request #7 from richardrigutins/stable
Browse files Browse the repository at this point in the history
Update Aspire.Hosting packages to stable versions
  • Loading branch information
richardrigutins authored Jul 21, 2024
2 parents 50ac0ae + 6b88582 commit 2db011b
Show file tree
Hide file tree
Showing 19 changed files with 86 additions and 64 deletions.
2 changes: 1 addition & 1 deletion src/VirgilAgent.Aspire.AppHost/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
var builder = DistributedApplication.CreateBuilder(args);

var redis = builder.AddRedisContainer("redis");
var redis = builder.AddRedis("redis");

var chatService = builder.AddProject<Projects.VirgilAgent_ChatService>("chatservice")
.WithReference(redis);
Expand Down
11 changes: 6 additions & 5 deletions src/VirgilAgent.Aspire.AppHost/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15173",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:16036"
}
"environmentVariables": {
"ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true",
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:16036"
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting" Version="8.0.0-preview.1.23557.2" />
<PackageReference Include="Aspire.Hosting.AppHost" Version="8.0.2" />
<PackageReference Include="Aspire.Hosting.Redis" Version="8.0.2" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/VirgilAgent.Aspire.ServiceDefaults/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBu
http.AddStandardResilienceHandler();

// Turn on service discovery by default
http.UseServiceDiscovery();
http.AddServiceDiscovery();
});

return builder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />

<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="8.0.0-preview.1.23557.2" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.7.0-alpha.1" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.7.0-alpha.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.8.1" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="8.7.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="8.0.2" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.GrpcNetClient" Version="1.6.0-beta.2" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.8.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.5.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
</ItemGroup>

</Project>
20 changes: 11 additions & 9 deletions src/VirgilAgent.BotService/Bots/VirgilBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivi

protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
// No new members that are not the bot itself, so no need to send a welcome message.
if (!membersAdded.Any(m => m.Id != turnContext.Activity.Recipient.Id))
{
return;
}

// Try to get the user locale
string? locale = turnContext.Activity.GetLocale();

Expand All @@ -52,13 +58,7 @@ protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersA
// Get the start message from the chat API.
string welcomeText = await StartConversationAsync(locale, conversationId);

foreach (var member in membersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync(MessageFactory.Text(welcomeText, welcomeText), cancellationToken);
}
}
await turnContext.SendActivityAsync(MessageFactory.Text(welcomeText), cancellationToken);
}

private async Task<string> GetChatResponseAsync(string message, string conversationId)
Expand Down Expand Up @@ -94,7 +94,8 @@ private async Task<IEnumerable<SuggestedAction>> TryGetSuggestedActions(string m
}
catch (Exception ex)
{
// Log the error and return an empty list, without surfacing the error to the user.
// Any error while getting suggestions should not block the main flow.
// The error is only logged and an empty list is returned.
_logger.LogError(ex, "An error occurred while trying to get suggestions from API: {errorMessage}", ex.Message);
return [];
}
Expand All @@ -104,7 +105,8 @@ private async Task<string> StartConversationAsync(string? locale = null, string?
{
try
{
ChatMessageResponse chatResponse = await _chatApiClient.StartConversationAsync(locale, conversationId);
StartConversationRequest request = new(locale, conversationId);
ChatMessageResponse chatResponse = await _chatApiClient.StartConversationAsync(request);

string responseMessage = chatResponse.Message;

Expand Down
9 changes: 6 additions & 3 deletions src/VirgilAgent.BotService/Services/ChatApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ internal class ChatApiClient(HttpClient httpClient)
{
private readonly HttpClient _httpClient = httpClient;

public async Task<ChatMessageResponse> StartConversationAsync(string? locale = null, string? conversationId = null)
public async Task<ChatMessageResponse> StartConversationAsync(StartConversationRequest? request)
{
HttpResponseMessage response = await _httpClient.GetAsync("/start");
string jsonBody = JsonSerializer.Serialize(request);
using HttpContent content = new StringContent(jsonBody, Encoding.UTF8, MediaTypeNames.Application.Json);

HttpResponseMessage response = await _httpClient.PostAsync("/start", content);

if (!response.IsSuccessStatusCode)
{
Expand All @@ -28,7 +31,7 @@ public async Task<ChatMessageResponse> StartConversationAsync(string? locale = n
public async Task<ChatMessageResponse> SendMessageAsync(ChatMessageRequest request)
{
string jsonBody = JsonSerializer.Serialize(request);
HttpContent content = new StringContent(jsonBody, Encoding.UTF8, MediaTypeNames.Application.Json);
using HttpContent content = new StringContent(jsonBody, Encoding.UTF8, MediaTypeNames.Application.Json);

HttpResponseMessage response = await _httpClient.PostAsync("/chat", content);

Expand Down
6 changes: 6 additions & 0 deletions src/VirgilAgent.BotService/Services/SuggestionsApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ internal class SuggestionsApiClient(HttpClient httpClient)

public async Task<IEnumerable<SuggestedAction>> GetSuggestedActionsAsync(string message)
{
// Don't send empty messages.
if (string.IsNullOrWhiteSpace(message))
{
return [];
}

// Encode the message.
string encodedMessage = Uri.EscapeDataString(message);
string url = $"/suggestions?message={encodedMessage}";
Expand Down
4 changes: 2 additions & 2 deletions src/VirgilAgent.BotService/VirgilAgent.BotService.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.1" />
<PackageReference Include="Microsoft.Bot.Builder.Integration.AspNet.Core" Version="4.17.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.7" />
<PackageReference Include="Microsoft.Bot.Builder.Integration.AspNet.Core" Version="4.22.7" />
</ItemGroup>

<ItemGroup>
Expand Down
9 changes: 6 additions & 3 deletions src/VirgilAgent.ChatService/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,15 @@

app.MapDefaultEndpoints();

app.MapGet("/start",
app.MapPost("/start",
async (
[FromServices] ChatService chatService,
[FromQuery] string? locale,
[FromQuery] string? conversationId) =>
[FromBody] StartConversationRequest? request) =>
{
// Get the conversation id and locale from the request.
string? conversationId = request?.ConversationId;
string? locale = request?.Locale;

// Create a new conversation with the initial message.
Conversation conversation = await chatService.StartConversationAsync(conversationId, locale);

Expand Down
7 changes: 2 additions & 5 deletions src/VirgilAgent.ChatService/Services/ChatService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ public async Task<string> GetChatResponseAsync(
Conversation? conversation = _cache.Get<Conversation?>(conversationId, null);
if (conversation is null)
{
_logger.LogInformation(
"Conversation with id {conversationId} not found in cache, it will be initialized",
conversationId);
_logger.LogInformation("Conversation not found in cache, it will be initialized");
conversation = BuildEmptyConversation(conversationId);
}

Expand Down Expand Up @@ -120,8 +118,7 @@ private void AddMessageToConversation(Conversation conversation, ConversationMes
if (conversation.Messages.Count > _chatOptions.MaxSavedMessages)
{
_logger.LogInformation(
"Conversation with id {conversationId} has reached the max length ({maxLength}), the oldest message will be removed",
conversation.Id,
"Conversation has reached the max length ({maxLength}), the oldest message will be removed",
_chatOptions.MaxSavedMessages);

conversation.Messages.RemoveAt(0);
Expand Down
4 changes: 2 additions & 2 deletions src/VirgilAgent.ChatService/VirgilAgent.ChatService.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
<ItemGroup>
<PackageReference Include="Azure.AI.OpenAI" Version="1.0.0-beta.9" />
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.2.2" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.7" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/VirgilAgent.Core/Cache/InMemoryCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public void Set<TValue>(string key, TValue value, TimeSpan? expiresIn = null)
/// <inheritdoc />
public bool ContainsKey(string key)
{
return _cache.ContainsKey(key) && !(_cache[key].Expiration.HasValue && _cache[key].Expiration < DateTime.Now);
return _cache.TryGetValue(key, out var value) && !(value.Expiration.HasValue && value.Expiration < DateTime.Now);
}

/// <inheritdoc />
Expand Down
12 changes: 4 additions & 8 deletions src/VirgilAgent.Core/Cache/RedisCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,10 @@ public void Remove(string key)
/// <inheritdoc />
public void Clear()
{
foreach (var endPoint in _database.Multiplexer.GetEndPoints())
{
var server = _database.Multiplexer.GetServer(endPoint);
foreach (var key in server.Keys())
{
_database.KeyDelete(key);
}
}
_database.Multiplexer.GetEndPoints()
.SelectMany(endPoint => _database.Multiplexer.GetServer(endPoint).Keys())
.ToList()
.ForEach(key => _database.KeyDelete(key));
}

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static IHostApplicationBuilder AddCache(
builder.Services.AddSingleton<ICache>(new InMemoryCache(cacheOptions.ExpirationInSeconds));
break;
case CacheType.Redis:
builder.AddRedis(cacheOptions.ConnectionString ?? string.Empty);
builder.AddRedisClient(cacheOptions.ConnectionString ?? string.Empty);
builder.Services.AddSingleton<ICache>((services) =>
{
IConnectionMultiplexer redis = services.GetRequiredService<IConnectionMultiplexer>();
Expand Down
8 changes: 8 additions & 0 deletions src/VirgilAgent.Core/StartConversationRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace VirgilAgent.Core;

/// <summary>
/// Data structure for sending a request to start a conversation.
/// </summary>
public record StartConversationRequest(
string? Locale,
string? ConversationId);
4 changes: 2 additions & 2 deletions src/VirgilAgent.Core/VirgilAgent.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.StackExchange.Redis" Version="8.0.0-preview.1.23557.2" />
<PackageReference Include="Aspire.StackExchange.Redis" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="StackExchange.Redis" Version="2.7.4" />
<PackageReference Include="StackExchange.Redis" Version="2.8.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -116,27 +116,32 @@ public async Task<List<SuggestedAction>> GetSuggestedActionsAsync(
/// <returns><see langword="true"/> if the parsing was successful, otherwise <see langword="false"/>.</returns>
private static bool TryParseLine(string line, out SuggestedAction? suggestedAction)
{
suggestedAction = default;

if (string.IsNullOrWhiteSpace(line))
{
suggestedAction = default;
// No suggestion to parse.
return false;
}

try
string[] parts = line.Split('|');
if (parts.Length < 2)
{
string[] parts = line.Split('|');
string text = parts[0];
ActionType actionType = Enum.Parse<ActionType>(parts[1]);
string? actionData = parts.Length > 2 ? parts[2] : null;

suggestedAction = new(text, actionType, actionData);
return true;
// Invalid suggestion format.
return false;
}
catch

string text = parts[0];
if (!Enum.TryParse(parts[1], out ActionType actionType))
{
suggestedAction = default;
// Invalid action type.
return false;
}

string? actionData = parts.Length > 2 ? parts[2] : null;

suggestedAction = new SuggestedAction(text, actionType, actionData);
return true;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
<ItemGroup>
<PackageReference Include="Azure.AI.OpenAI" Version="1.0.0-beta.9" />
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.2.2" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.7" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>

<ItemGroup>
Expand Down

0 comments on commit 2db011b

Please sign in to comment.