Skip to content

Mariomedhat899/AiMemory

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

AiMemory 🧠

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.

License .NET 8 C# Swagger AI Ready


πŸ“‹ Table of Contents


✨ Why AiMemory?

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.


🎯 Key Features

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

πŸ—οΈ Architecture Overview

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

πŸ› οΈ Tech Stack

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

πŸš€ Getting Started

Prerequisites

Quick Start

# 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

About

🧠 .NET 8 backend for persistent AI memory | Context storage & retrieval for LLMs | Async API + EF Core | OpenAI/Semantic Kernel ready

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages