Устранение неполадок
Частые проблемы и решения для SmartRAG
Частые проблемы
Частые проблемы и решения, с которыми вы можете столкнуться при использовании SmartRAG.
Проблемы компиляции
Внимание
Сначала создайте чистое решение для устранения ошибок компиляции.
Ошибка пакета NuGet
# Чистое решение
dotnet clean
dotnet restore
dotnet build
Конфликт зависимостей
<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" />
Проблемы времени выполнения
Ошибка API ключа
Ошибка
UnauthorizedAccessException: API ключ недействителен или отсутствует.
// appsettings.json
{
"SmartRAG": {
"AIProvider": "Anthropic",
"Anthropic": {
"ApiKey": "your-api-key-here",
"Model": "claude-3-sonnet-20240229"
}
}
}
Таймаут соединения
services.AddSmartRAG(configuration, options =>
{
options.AIProvider = AIProvider.Anthropic;
options.StorageProvider = StorageProvider.Qdrant;
options.MaxRetryAttempts = 5;
options.RetryDelayMs = 2000;
options.RetryPolicy = RetryPolicy.ExponentialBackoff;
});
Проблемы производительности
Медленный поиск
Совет
Оптимизируйте размеры чанков для улучшения производительности.
services.AddSmartRAG(configuration, options =>
{
options.MaxChunkSize = 1000; // Рекомендуется 1000-1500
options.ChunkOverlap = 200; // Рекомендуется 200-300
options.MaxRetryAttempts = 3;
});
Использование памяти
// Используйте потоковую передачу для больших файлов
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;
}
Проблемы конфигурации
Неправильный выбор провайдера
// Правильная конфигурация
services.AddSmartRAG(configuration, options =>
{
options.AIProvider = AIProvider.Anthropic;
options.StorageProvider = StorageProvider.Qdrant;
// Необходимые настройки для Qdrant
options.Qdrant = new QdrantOptions
{
Host = "localhost",
Port = 6333,
CollectionName = "smartrag_documents"
};
});
Отсутствующие зависимости
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Необходимые сервисы
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// SmartRAG сервисы
builder.Services.AddSmartRAG(builder.Configuration, options =>
{
options.AIProvider = AIProvider.Anthropic;
options.StorageProvider = StorageProvider.Qdrant;
});
var app = builder.Build();
// Пайплайн middleware
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Отладка
Техники отладки для вашего SmartRAG приложения.
Конфигурация логирования
// appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"SmartRAG": "Debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
Детальная отладка
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("Загрузка документа начата: {FileName}, Размер: {Size}",
file?.FileName, file?.Length);
try
{
if (file == null || file.Length == 0)
{
_logger.LogWarning("Файл null или пустой");
return BadRequest("Файл не выбран");
}
_logger.LogDebug("Файл проверен, начинается обработка");
var document = await _documentService.UploadDocumentAsync(file);
_logger.LogInformation("Документ успешно загружен: {DocumentId}", document.Id);
return Ok(document);
}
catch (ArgumentException ex)
{
_logger.LogError(ex, "Неверный формат файла: {FileName}", file?.FileName);
return BadRequest($"Неверный формат файла: {ex.Message}");
}
catch (UnauthorizedAccessException ex)
{
_logger.LogError(ex, "Ошибка API ключа");
return Unauthorized("Неверный API ключ");
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "Ошибка сетевого подключения");
return StatusCode(503, "Сервис временно недоступен");
}
catch (Exception ex)
{
_logger.LogError(ex, "Произошла неожиданная ошибка");
return StatusCode(500, "Внутренняя ошибка сервера");
}
}
}
Мониторинг производительности
[HttpPost("search")]
public async Task<ActionResult<IEnumerable<DocumentChunk>>> SearchDocuments(
[FromQuery] string query,
[FromQuery] int maxResults = 10)
{
var stopwatch = Stopwatch.StartNew();
_logger.LogInformation("Поиск начат: {Query}", query);
try
{
var results = await _documentService.SearchDocumentsAsync(query, maxResults);
stopwatch.Stop();
_logger.LogInformation("Поиск завершен: {Query}, Результаты: {Count}, Время: {Duration}ms",
query, results.Count(), stopwatch.ElapsedMilliseconds);
return Ok(results);
}
catch (Exception ex)
{
stopwatch.Stop();
_logger.LogError(ex, "Ошибка поиска: {Query}, Время: {Duration}ms",
query, stopwatch.ElapsedMilliseconds);
throw;
}
}
Тестирование
Методы тестирования вашего SmartRAG приложения.
Модульные тесты
[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);
}
Интеграционные тесты
[Test]
public async Task SearchDocuments_IntegrationTest()
{
// Arrange
var host = CreateTestHost();
using var scope = host.Services.CreateScope();
var documentService = scope.ServiceProvider.GetRequiredService<IDocumentService>();
// Загрузить тестовые данные
var testFile = CreateTestFile("test-document.txt", "Это тестовый документ.");
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 для тестов
});
})
.Build();
}
API тесты
[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);
}
Получение помощи
Методы получения помощи с проблемами SmartRAG.
GitHub Issues
GitHub
Сообщайте о проблемах на GitHub и получайте поддержку сообщества.
Поддержка по email
Получайте прямую поддержку по email: b.yerlikaya@outlook.com
Документация
Профилактика
Методы предотвращения проблем в вашем SmartRAG приложении.
Лучшие практики
- Обработка ошибок: Оберните все API вызовы в try-catch блоки
- Логирование: Выполняйте детальное логирование и настройте уровни логов соответствующим образом
- Производительность: Оптимизируйте размеры чанков и используйте потоковую передачу для больших файлов
- Безопасность: Безопасно храните API ключи
- Тестирование: Напишите комплексные тесты и запускайте их в CI/CD пайплайнах
Проверка конфигурации
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
{
// Простой тестовый запрос
var results = await _documentService.SearchDocumentsAsync("health check", 1);
return HealthCheckResult.Healthy("SmartRAG сервис работает");
}
catch (Exception ex)
{
_logger.LogError(ex, "Проверка здоровья SmartRAG не удалась");
return HealthCheckResult.Unhealthy("SmartRAG сервис не работает", ex);
}
}
}