Fehlerbehebung
Häufige Probleme und Lösungen für SmartRAG
Häufige Probleme
Häufige Probleme und Lösungen, die Sie bei der Verwendung von SmartRAG begegnen können.
Kompilierungsprobleme
Achtung
Erstellen Sie zuerst eine saubere Lösung, um Kompilierungsfehler zu beheben.
NuGet-Paketfehler
# Saubere Lösung
dotnet clean
dotnet restore
dotnet build
Abhängigkeitskonflikt
<PackageReference Include="SmartRAG" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
Laufzeitprobleme
API-Schlüssel-Fehler
Fehler
UnauthorizedAccessException: API-Schlüssel ungültig oder fehlend.
// appsettings.json
{
"SmartRAG": {
"AIProvider": "Anthropic",
"Anthropic": {
"ApiKey": "your-api-key-here",
"Model": "claude-3-sonnet-20240229"
}
}
}
Verbindungs-Timeout
services.AddSmartRAG(configuration, options =>
{
options.AIProvider = AIProvider.Anthropic;
options.StorageProvider = StorageProvider.Qdrant;
options.MaxRetryAttempts = 5;
options.RetryDelayMs = 2000;
options.RetryPolicy = RetryPolicy.ExponentialBackoff;
});
Leistungsprobleme
Langsame Suche
Tipp
Optimieren Sie die Chunk-Größen, um die Leistung zu verbessern.
services.AddSmartRAG(configuration, options =>
{
options.MaxChunkSize = 1000; // 1000-1500 empfohlen
options.ChunkOverlap = 200; // 200-300 empfohlen
options.MaxRetryAttempts = 3;
});
Speicherverbrauch
// Verwenden Sie Streaming für große Dateien
public async Task<Document> UploadLargeDocumentAsync(IFormFile file)
{
using var stream = file.OpenReadStream();
var chunks = await _documentParserService.ChunkTextAsync(stream, 1000, 200);
var document = new Document
{
Id = Guid.NewGuid().ToString(),
FileName = file.FileName,
Content = await _documentParserService.ParseDocumentAsync(file),
ContentType = file.ContentType,
FileSize = file.Length,
UploadedAt = DateTime.UtcNow
};
return document;
}
Konfigurationsprobleme
Falsche Provider-Auswahl
// Richtige Konfiguration
services.AddSmartRAG(configuration, options =>
{
options.AIProvider = AIProvider.Anthropic;
options.StorageProvider = StorageProvider.Qdrant;
// Erforderliche Einstellungen für Qdrant
options.Qdrant = new QdrantOptions
{
Host = "localhost",
Port = 6333,
CollectionName = "smartrag_documents"
};
});
Fehlende Abhängigkeiten
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Erforderliche Services
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// SmartRAG Services
builder.Services.AddSmartRAG(builder.Configuration, options =>
{
options.AIProvider = AIProvider.Anthropic;
options.StorageProvider = StorageProvider.Qdrant;
});
var app = builder.Build();
// Middleware-Pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Debugging
Debugging-Techniken für Ihre SmartRAG-Anwendung.
Protokollierungskonfiguration
// appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"SmartRAG": "Debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
Detailliertes Debugging
public class DocumentController : ControllerBase
{
private readonly IDocumentService _documentService;
private readonly ILogger<DocumentController> _logger;
public DocumentController(IDocumentService documentService, ILogger<DocumentController> logger)
{
_documentService = documentService;
_logger = logger;
}
[HttpPost("upload")]
public async Task<ActionResult<Document>> UploadDocument(IFormFile file)
{
_logger.LogInformation("Dokument-Upload gestartet: {FileName}, Größe: {Size}",
file?.FileName, file?.Length);
try
{
if (file == null || file.Length == 0)
{
_logger.LogWarning("Datei ist null oder leer");
return BadRequest("Keine Datei ausgewählt");
}
_logger.LogDebug("Datei validiert, Verarbeitung beginnt");
var document = await _documentService.UploadDocumentAsync(file);
_logger.LogInformation("Dokument erfolgreich hochgeladen: {DocumentId}", document.Id);
return Ok(document);
}
catch (ArgumentException ex)
{
_logger.LogError(ex, "Ungültiges Dateiformat: {FileName}", file?.FileName);
return BadRequest($"Ungültiges Dateiformat: {ex.Message}");
}
catch (UnauthorizedAccessException ex)
{
_logger.LogError(ex, "API-Schlüssel-Fehler");
return Unauthorized("Ungültiger API-Schlüssel");
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "Netzwerkverbindungsfehler");
return StatusCode(503, "Service vorübergehend nicht verfügbar");
}
catch (Exception ex)
{
_logger.LogError(ex, "Unerwarteter Fehler aufgetreten");
return StatusCode(500, "Interner Serverfehler");
}
}
}
Leistungsüberwachung
[HttpPost("search")]
public async Task<ActionResult<IEnumerable<DocumentChunk>>> SearchDocuments(
[FromQuery] string query,
[FromQuery] int maxResults = 10)
{
var stopwatch = Stopwatch.StartNew();
_logger.LogInformation("Suche gestartet: {Query}", query);
try
{
var results = await _documentService.SearchDocumentsAsync(query, maxResults);
stopwatch.Stop();
_logger.LogInformation("Suche abgeschlossen: {Query}, Ergebnisse: {Count}, Dauer: {Duration}ms",
query, results.Count(), stopwatch.ElapsedMilliseconds);
return Ok(results);
}
catch (Exception ex)
{
stopwatch.Stop();
_logger.LogError(ex, "Suchfehler: {Query}, Dauer: {Duration}ms",
query, stopwatch.ElapsedMilliseconds);
throw;
}
}
Testen
Methoden zum Testen Ihrer SmartRAG-Anwendung.
Unit-Tests
[Test]
public async Task UploadDocument_ValidFile_ReturnsDocument()
{
// Arrange
var mockFile = new Mock<IFormFile>();
mockFile.Setup(f => f.FileName).Returns("test.pdf");
mockFile.Setup(f => f.Length).Returns(1024);
mockFile.Setup(f => f.ContentType).Returns("application/pdf");
var mockDocumentService = new Mock<IDocumentService>();
var expectedDocument = new Document { Id = "test-id", FileName = "test.pdf" };
mockDocumentService.Setup(s => s.UploadDocumentAsync(It.IsAny<IFormFile>()))
.ReturnsAsync(expectedDocument);
var controller = new DocumentController(mockDocumentService.Object, Mock.Of<ILogger<DocumentController>>());
// Act
var result = await controller.UploadDocument(mockFile.Object);
// Assert
Assert.IsInstanceOf<OkObjectResult>(result);
var okResult = result as OkObjectResult;
Assert.AreEqual(expectedDocument, okResult.Value);
}
Integrationstests
[Test]
public async Task SearchDocuments_IntegrationTest()
{
// Arrange
var host = CreateTestHost();
using var scope = host.Services.CreateScope();
var documentService = scope.ServiceProvider.GetRequiredService<IDocumentService>();
// Testdaten laden
var testFile = CreateTestFile("test-document.txt", "Dies ist ein Testdokument.");
await documentService.UploadDocumentAsync(testFile);
// Act
var results = await documentService.SearchDocumentsAsync("test", 5);
// Assert
Assert.IsNotNull(results);
Assert.IsTrue(results.Any());
Assert.IsTrue(results.First().Content.Contains("test"));
}
private IHost CreateTestHost()
{
return Host.CreateDefaultBuilder()
.ConfigureServices((context, services) =>
{
services.AddSmartRAG(context.Configuration, options =>
{
options.AIProvider = AIProvider.Anthropic;
options.StorageProvider = StorageProvider.InMemory; // InMemory für Tests verwenden
});
})
.Build();
}
API-Tests
[Test]
public async Task UploadDocument_ApiTest()
{
// Arrange
var client = _factory.CreateClient();
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(File.ReadAllBytes("test-file.pdf"));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/pdf");
content.Add(fileContent, "file", "test-file.pdf");
// Act
var response = await client.PostAsync("/api/document/upload", content);
// Assert
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
var document = JsonSerializer.Deserialize<Document>(responseContent);
Assert.IsNotNull(document);
Assert.AreEqual("test-file.pdf", document.FileName);
}
Hilfe erhalten
Methoden, um Hilfe bei SmartRAG-Problemen zu erhalten.
GitHub Issues
GitHub
Melden Sie Probleme auf GitHub und erhalten Sie Community-Unterstützung.
E-Mail-Support
Erhalten Sie direkten E-Mail-Support: b.yerlikaya@outlook.com
Dokumentation
Prävention
Methoden zur Vermeidung von Problemen in Ihrer SmartRAG-Anwendung.
Beste Praktiken
- Fehlerbehandlung: Wickeln Sie alle API-Aufrufe in try-catch-Blöcke ein
- Protokollierung: Führen Sie detaillierte Protokollierung durch und konfigurieren Sie Log-Levels angemessen
- Leistung: Optimieren Sie Chunk-Größen und verwenden Sie Streaming für große Dateien
- Sicherheit: Speichern Sie API-Schlüssel sicher
- Tests: Schreiben Sie umfassende Tests und führen Sie sie in CI/CD-Pipelines aus
Konfigurationsprüfung
public class SmartRAGHealthCheck : IHealthCheck
{
private readonly IDocumentService _documentService;
private readonly ILogger<SmartRAGHealthCheck> _logger;
public SmartRAGHealthCheck(IDocumentService documentService, ILogger<SmartRAGHealthCheck> logger)
{
_documentService = documentService;
_logger = logger;
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
// Einfache Testabfrage
var results = await _documentService.SearchDocumentsAsync("health check", 1);
return HealthCheckResult.Healthy("SmartRAG-Service läuft");
}
catch (Exception ex)
{
_logger.LogError(ex, "SmartRAG-Gesundheitsprüfung fehlgeschlagen");
return HealthCheckResult.Unhealthy("SmartRAG-Service läuft nicht", ex);
}
}
}