AI-Studio/app/MindWork AI Studio/Tools/Services/RustService.Retrieval.cs

53 lines
1.7 KiB
C#
Raw Normal View History

using System.Text;
using System.Text.Json;
namespace AIStudio.Tools.Services;
public sealed partial class RustService
{
2025-06-28 20:34:15 +00:00
public async Task<string> ReadArbitraryFileData(string path, int maxChunks)
{
var requestUri = $"/retrieval/fs/extract?path={Uri.EscapeDataString(path)}";
var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
var response = await this.http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
2025-06-28 20:36:06 +00:00
if (!response.IsSuccessStatusCode)
return string.Empty;
await using var stream = await response.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
var resultBuilder = new StringBuilder();
2025-06-28 20:34:15 +00:00
var chunkCount = 0;
2025-06-28 20:34:15 +00:00
while (!reader.EndOfStream && chunkCount < maxChunks)
{
var line = await reader.ReadLineAsync();
if (string.IsNullOrWhiteSpace(line))
2025-06-28 20:36:01 +00:00
continue;
2025-06-28 20:35:29 +00:00
if (!line.StartsWith("data:", StringComparison.InvariantCulture))
continue;
var jsonContent = line[5..];
try
{
var sseEvent = JsonSerializer.Deserialize<SseEvent>(jsonContent);
2025-06-28 20:36:06 +00:00
if (sseEvent is not null)
{
var content = await SseHandler.ProcessEventAsync(sseEvent, false);
resultBuilder.Append(content);
2025-06-28 20:34:15 +00:00
chunkCount++;
}
}
2025-06-28 20:36:06 +00:00
catch (JsonException)
{
2025-06-28 21:07:15 +00:00
this.logger?.LogError("Failed to deserialize SSE event: {JsonContent}", jsonContent);
2025-06-28 20:36:06 +00:00
}
}
2025-06-28 20:36:01 +00:00
return resultBuilder.ToString();
}
}