A persistent memory backend for AI agents built with .NET 8 Web API. Enable long-term context retention, semantic organization, and seamless conversation continuity for LLM-powered applications.
- β¨ Why AiMemory?
- π― Key Features
- ποΈ Architecture Overview
- π οΈ Tech Stack
- π Getting Started
- π API Usage Examples
- π€ AI Integration Guide
- ποΈ Data Model & Storage
- π§ͺ Testing & Development
- π€ Contributing
- π License
- π¨βπ» Author
Standard LLM integrations suffer from context amnesia β every conversation starts fresh. AiMemory solves this by providing:
| Problem | AiMemory Solution |
|---|---|
| β No memory between sessions | β Persistent contextual storage with user/session IDs |
| β Flat conversation history | β Semantic organization with metadata tagging |
| β Manual context management | β Clean REST API for injection & retrieval |
| β Scaling challenges | β Async-first architecture for high-frequency AI requests |
π‘ Think of AiMemory as a hippocampus for your AI agents β storing, organizing, and recalling what matters.
| Feature | Description |
|---|---|
| πΉ Context Persistence | Store user interactions, AI responses, and metadata with TTL support |
| πΉ Semantic Organization | Tag, categorize, and search memories by intent, topic, or custom metadata |
| πΉ Session Management | Isolate memories by user ID, session ID, or conversation thread |
| πΉ Async-First Design | Non-blocking I/O for high-throughput AI agent workloads |
| πΉ Flexible Schema | Extendable memory model for custom AI use cases |
| πΉ RESTful API | Clean endpoints for CRUD operations on memory entries |
| πΉ Swagger Documentation | Interactive API explorer with example payloads |
| πΉ AI SDK Ready | Designed for easy integration with OpenAI, Semantic Kernel, or custom LLMs |
AiMemory/ βββ Core/ # Domain Layer β βββ Entities/ # MemoryEntry, UserContext, Session β βββ Interfaces/ # IMemoryRepository, IMemoryService β βββ Specifications/ # Query filters (by user, date, tags, etc.) β βββ Infrastructure/ # External Implementations β βββ Data/ # EF Core DbContext + Migrations β βββ Repositories/ # EF Core repository implementations β βββ Services/ # Memory orchestration + AI adapter interfaces β βββ Shared/ # Cross-cutting Concerns β βββ DTOs/ # Request/Response models (MemoryDto, QueryDto) β βββ Exceptions/ # Custom error types (MemoryNotFoundException) β βββ Helpers/ # Extensions, serializers, utils β βββ AiMemory.API/ # Presentation Layer βββ Controllers/ # MemoryController, SessionController βββ Middleware/ # Global error handling, logging βββ Properties/ # appsettings, launchSettings βββ Program.cs # DI setup, Swagger config, CORS
Design Patterns:
- β Clean Architecture β Separation of concerns, testable layers
- β Repository + Unit of Work β Abstracted, transactional data access
- β Specification Pattern β Reusable, composable query logic
- β Dependency Injection β Built-in .NET 8 DI container
- β CQRS-Lite β Separated read/write models for memory operations
| Layer | Technology |
|---|---|
| Framework | .NET 8 Web API (Minimal APIs or Controllers) |
| Language | C# 12 with modern async/await patterns |
| ORM | Entity Framework Core 8 |
| Database | SQL Server / PostgreSQL / SQLite (provider-agnostic) |
| Caching | Optional: Redis for frequent memory lookups |
| AI Integration | OpenAI SDK / Semantic Kernel / Custom adapters |
| Docs | Swagger/OpenAPI 3.0 + XML comments |
| Testing | xUnit + Moq ready structure |
| Observability | Serilog + Application Insights ready |
- .NET 8 SDK
- SQL Server / PostgreSQL / or SQLite
- Visual Studio 2022 or VS Code + C# Dev Kit
- Postman or Bruno for API testing
# 1. Clone the repository
git clone https://github.com/Mariomedhat899/AiMemory.git
cd AiMemory
# 2. Restore dependencies
dotnet restore
# 3. Configure connection string
# Edit: AiMemory.API/appsettings.json
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=AiMemory;Trusted_Connection=True;"
}
# 4. Apply Entity Framework migrations
Update-Database
# OR via CLI:
dotnet ef database update
# 5. Run the API
dotnet run --project AiMemory.API
# Or press F5 in Visual Studio
π API Usage Examples
β Store a Memory
POST /api/memory
Content-Type: application/json
{
"userId": "user_123",
"sessionId": "session_abc",
"content": "User prefers dark mode and notifications disabled",
"metadata": {
"category": "preferences",
"tags": ["ui", "settings"],
"importance": "high"
},
"ttlHours": 720
}
π Retrieve Memories
GET /api/memory?userId=user_123&tags=preferences&limit=10
Authorization: Bearer your_token_if_enabled
Response:
{
"memories": [
{
"id": "mem_xyz",
"content": "User prefers dark mode and notifications disabled",
"metadata": { "category": "preferences", "tags": ["ui", "settings"] },
"createdAt": "2026-05-17T10:30:00Z",
"relevanceScore": 0.95
}
],
"totalCount": 1,
"hasMore": false
}
ποΈ Delete Memory
DELETE /api/memory/{memoryId}
π‘ All endpoints support filtering by userId, sessionId, tags, dateRange, and metadata fields.
π€ AI Integration Guide
With OpenAI SDK
// 1. Retrieve relevant memories before calling LLM
var memories = await _memoryService.GetMemoriesAsync(
userId: "user_123",
tags: new[] { "preferences", "history" },
limit: 5);
// 2. Inject into system prompt
var systemPrompt = $@"
You are a helpful assistant.
User context from memory:
{string.Join("\n", memories.Select(m => m.Content))}
Respond naturally while respecting stored preferences.";
// 3. Call OpenAI
var response = await openAiChatClient.CompleteAsync(systemPrompt, userMessage);
// 4. Optionally store new memory from interaction
await _memoryService.StoreMemoryAsync(new MemoryEntry {
UserId = "user_123",
Content = $"User asked about: {userMessage}",
Metadata = new { category = "interaction", timestamp = DateTime.UtcNow }
});
With Semantic Kernel
// Register AiMemory as a SK plugin
kernel.Plugins.AddFromObject(new MemoryPlugin(_memoryService));
// Use in prompt function
var prompt = @"
{{$input}}
Context from memory: {{Memory.GetRelevant $userId $tags}}
";
π See /examples folder for full integration samples with OpenAI, Semantic Kernel, and custom LLM adapters.
ποΈ Data Model & Storage
Core Entity: MemoryEntry
public class MemoryEntry
{
public Guid Id { get; set; }
public string UserId { get; set; } // Indexed for fast lookup
public string? SessionId { get; set; } // Optional conversation thread
public string Content { get; set; } // The actual memory text
public string? MetadataJson { get; set; } // Flexible JSON metadata
public DateTime CreatedAt { get; set; }
public DateTime? ExpiresAt { get; set; } // TTL support
public int RelevanceScore { get; set; } // For semantic ranking
}
Indexing Strategy
β
UserId + CreatedAt β Fast user timeline queries
β
MetadataJson (partial) β Filter by category/tags via JSON functions
β
Full-text search ready β Enable for semantic content lookup
Migration Example
# Add new memory field
Add-Migration AddRelevanceScoreToMemory
# Update database
Update-Database
# Seed initial schema
dotnet run -- --seed
π§ͺ Testing & Development
# Run unit tests
dotnet test
# Run integration tests (requires test DB)
dotnet test --filter "Category=Integration"
# Watch mode for development
dotnet watch run --project AiMemory.API
# Generate Swagger JSON
curl https://localhost:7001/swagger/v1/swagger.json -o openapi.json
Test Coverage Goals:
β
Core domain logic: 90%+
β
API endpoints: 80%+
β
Integration tests: Critical paths covered
π€ Contributing
Contributions are welcome! Please follow these steps:
Fork the repository
Create your feature branch (git checkout -b feat/add-semantic-search)
Commit your changes (git commit -m 'feat: add vector similarity search')
Push to the branch (git push origin feat/add-semantic-search)
Open a Pull Request with a clear description and tests
Development Guidelines
Follow C# coding conventions & .editorconfig
Add XML comments for public APIs (auto-generates Swagger docs)
Include unit tests for new services/controllers
Use conventional commits: feat:, fix:, docs:, refactor:, test:
Update API examples if endpoints change
π License
Distributed under the MIT License. See LICENSE for more information.
π¨βπ» Author
Mario Medhat
GitHub: @Mariomedhat899
.NET Backend Developer | AI Infrastructure Enthusiast