Skip to content
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 @@ -22,7 +22,7 @@ ILogger<ElasticsearchAskAiMessageFeedbackGateway> logger
{
private readonly string _indexName = $"ask-ai-message-feedback-{appEnvironment.Current.ToStringFast(true)}";

public async Task RecordFeedbackAsync(AskAiMessageFeedbackRecord record, CancellationToken ctx)
public async Task<bool> RecordFeedbackAsync(AskAiMessageFeedbackRecord record, CancellationToken ctx)
{
var feedbackId = Guid.NewGuid();
var document = new MessageFeedbackDocument
Expand All @@ -47,18 +47,18 @@ public async Task RecordFeedbackAsync(AskAiMessageFeedbackRecord record, Cancell
record.MessageId,
response.ApiCallDetails.HttpStatusCode
);
return false;
Comment thread
infra-vault-gh-plugin-prod[bot] marked this conversation as resolved.
Resolved
}
else
{
logger.LogInformation(
"Message feedback recorded: {Reaction} for message {MessageId} in conversation {ConversationId}. ES _id: {EsId}, Index: {Index}",
record.Reaction,
record.MessageId,
record.ConversationId,
feedbackId,
_indexName
);
}

logger.LogInformation(
"Message feedback recorded: {Reaction} for message {MessageId} in conversation {ConversationId}. ES _id: {EsId}, Index: {Index}",
record.Reaction,
record.MessageId,
record.ConversationId,
feedbackId,
_indexName
);
return true;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ public interface IAskAiMessageFeedbackService
/// </summary>
/// <param name="record">The feedback record to store.</param>
/// <param name="ctx">Cancellation token.</param>
Task RecordFeedbackAsync(AskAiMessageFeedbackRecord record, CancellationToken ctx);
/// <returns><c>false</c> when the feedback could not be stored.</returns>
Task<bool> RecordFeedbackAsync(AskAiMessageFeedbackRecord record, CancellationToken ctx);
}

/// <summary>
Expand Down
14 changes: 0 additions & 14 deletions src/api/Elastic.Documentation.Api/Aws/IParameterProvider.cs

This file was deleted.

This file was deleted.

77 changes: 0 additions & 77 deletions src/api/Elastic.Documentation.Api/Aws/LocalParameterProvider.cs

This file was deleted.

44 changes: 29 additions & 15 deletions src/api/Elastic.Documentation.Api/MappingsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ namespace Elastic.Documentation.Api;

public static class MappingsExtension
{
// An ActivitySource stays registered with the runtime until disposed, so create each one once.
private static readonly ActivitySource AskAiActivitySource = new(TelemetryConstants.AskAiSourceName);
private static readonly ActivitySource AskAiFeedbackActivitySource = new(TelemetryConstants.AskAiFeedbackSourceName);

public static void MapElasticDocsApiEndpoints(this IEndpointRouteBuilder group)
{
_ = group.MapGet("/", () => Results.Empty);
Expand Down Expand Up @@ -46,13 +50,12 @@ Cancel ctx
context.Response.Headers.CacheControl = "no-cache";
context.Response.Headers.Connection = "keep-alive";

var askAiActivitySource = new ActivitySource(TelemetryConstants.AskAiSourceName);
logger.LogInformation(
"Starting AskAI chat with {AgentProvider} and {AgentId}",
streamTransformer.AgentProvider,
streamTransformer.AgentId
);
var activity = askAiActivitySource.StartActivity($"chat {streamTransformer.AgentProvider}", ActivityKind.Client);
var activity = AskAiActivitySource.StartActivity($"chat {streamTransformer.AgentProvider}", ActivityKind.Client);
_ = activity?.SetTag("gen_ai.operation.name", "chat");
_ = activity?.SetTag("gen_ai.provider.name", streamTransformer.AgentProvider);
_ = activity?.SetTag("gen_ai.agent.id", streamTransformer.AgentId);
Expand All @@ -65,18 +68,29 @@ Cancel ctx
logger.LogInformation("AskAI input message: <{ask_ai.input.message}>", SanitizeForLog(askAiRequest.Message));
logger.LogInformation("Streaming AskAI response");

var response = await askAiService.AskAi(askAiRequest, ctx);
Stream transformedStream;
try
{
var response = await askAiService.AskAi(askAiRequest, ctx);

var conversationId = response.GeneratedConversationId ?? askAiRequest.ConversationId;
if (conversationId is not null)
_ = activity?.SetTag("gen_ai.conversation.id", conversationId.ToString());
var conversationId = response.GeneratedConversationId ?? askAiRequest.ConversationId;
if (conversationId is not null)
_ = activity?.SetTag("gen_ai.conversation.id", conversationId.ToString());

var transformedStream = await streamTransformer.TransformAsync(
response.Stream,
response.GeneratedConversationId,
activity,
ctx
);
transformedStream = await streamTransformer.TransformAsync(
response.Stream,
response.GeneratedConversationId,
activity,
ctx
);
}
catch (Exception ex)
{
// The transformer ends the activity once it owns the stream; until then this handler must.
_ = activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
activity?.Dispose();
throw;
}
await transformedStream.CopyToAsync(context.Response.Body, ctx);
});
Comment thread
infra-vault-gh-plugin-prod[bot] marked this conversation as resolved.
Resolved

Expand All @@ -91,8 +105,7 @@ Cancel ctx
{
var euid = TryGetEuid(context);

var feedbackActivitySource = new ActivitySource(TelemetryConstants.AskAiFeedbackSourceName);
using var activity = feedbackActivitySource.StartActivity("record message-feedback", ActivityKind.Internal);
using var activity = AskAiFeedbackActivitySource.StartActivity("record message-feedback", ActivityKind.Internal);
_ = activity?.SetTag("gen_ai.conversation.id", request.ConversationId);
_ = activity?.SetTag("ask_ai.message.id", request.MessageId);
_ = activity?.SetTag("ask_ai.feedback.reaction", request.Reaction.ToString().ToLowerInvariant());
Expand All @@ -106,7 +119,8 @@ Cancel ctx

var record = new AskAiMessageFeedbackRecord(request.MessageId, request.ConversationId, request.Reaction, euid);

await feedbackService.RecordFeedbackAsync(record, ctx);
if (!await feedbackService.RecordFeedbackAsync(record, ctx))
return Results.StatusCode(StatusCodes.Status503ServiceUnavailable);
return Results.NoContent();
}).DisableAntiforgery();
}
Expand Down
24 changes: 19 additions & 5 deletions src/api/Elastic.Documentation.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Elastic.Documentation.Api.OpenTelemetry;
using Elastic.Documentation.Configuration;
using Elastic.Documentation.Configuration.Assembler;
using Elastic.Documentation.Search;
using Elastic.Documentation.Search.Common;
using Elastic.Documentation.ServiceDefaults;
using Elastic.Documentation.ServiceDefaults.Telemetry;
Expand Down Expand Up @@ -54,13 +55,26 @@

_ = app.Environment.IsDevelopment()
? app.UseDeveloperExceptionPage()
: app.UseExceptionHandler(err => err.Run(context =>
: app.UseExceptionHandler(err => err.Run(async context =>
{
var ex = context.Features.Get<IExceptionHandlerFeature>()?.Error;
if (ex != null)
logger.LogError(ex, "Unhandled exception on {Method} {Path}", context.Request.Method, context.Request.Path);
context.Response.StatusCode = 500;
return Task.CompletedTask;
ApiError error;
if (ex is SearchUnavailableException)
{
// Transient by construction (timeout, overload): tell clients and the CDN to retry instead of failing.
logger.LogWarning(ex, "Search unavailable on {Method} {Path}", context.Request.Method, context.Request.Path);
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
context.Response.Headers.RetryAfter = "5";
error = new ApiError("search_unavailable", ex.Message);
}
else
{
if (ex != null)
logger.LogError(ex, "Unhandled exception on {Method} {Path}", context.Request.Method, context.Request.Path);
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
error = new ApiError("internal_error", "An unexpected error occurred.");
}
await context.Response.WriteAsJsonAsync(error, ApiJsonContext.Default.ApiError);
}));

var api = app.MapGroup(SystemEnvironmentVariables.Instance.ApiPrefix);
Expand Down
4 changes: 4 additions & 0 deletions src/api/Elastic.Documentation.Api/SerializationContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ public record InputMessage(string Role, MessagePart[] Parts);

public record OutputMessage(string Role, MessagePart[] Parts, string FinishReason);

/// <summary>The body of an error response: a stable <paramref name="ErrorType"/> and a message for people.</summary>
public sealed record ApiError(string ErrorType, string Message);

[JsonSerializable(typeof(AskAiRequest))]
[JsonSerializable(typeof(AskAiMessageFeedbackRequest))]
[JsonSerializable(typeof(Reaction))]
Expand Down Expand Up @@ -47,5 +50,6 @@ public record OutputMessage(string Role, MessagePart[] Parts, string FinishReaso
[JsonSerializable(typeof(Search.ApiReference.ApiSummary))]
[JsonSerializable(typeof(Search.ApiReference.ApiOperationListResponse))]
[JsonSerializable(typeof(Search.ApiReference.ApiReferenceRejection))]
[JsonSerializable(typeof(ApiError))]
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
public partial class ApiJsonContext : JsonSerializerContext;
Loading
Loading