-
Notifications
You must be signed in to change notification settings - Fork 1
LLM_PLUGIN_DEVELOPMENT_GUIDE
Version: 1.0.0 (ThemisDB v1.3.0)
Date: December 2025
Status: Implementation Guide
This guide explains how to develop LLM plugins for ThemisDB, based on the architecture defined in AI_ECOSYSTEM_SHARDING_ARCHITECTURE.md.
ThemisDB's plugin-based LLM architecture enables:
- Multiple LLM backends (llama.cpp, vLLM, custom implementations)
- LoRA adapter management for domain-specific fine-tuning
- Distributed reasoning across sharded deployments
- Zero-copy integration with ThemisDB's vector storage
ILLMPlugin (llm/llm_plugin_interface.h)
β
LlamaCppPlugin (reference implementation)
β
Your Custom Plugin
- ILLMPlugin - Base interface all plugins must implement
- LLMPluginManager - Coordinates multiple LLM backends
- LlamaCppPlugin - Reference implementation using llama.cpp
- LLMPluginAdapter - Bridges to ThemisDB's unified plugin system
// my_llm_plugin.h
#include "llm/llm_plugin_interface.h"
namespace themis {
namespace llm {
class MyLLMPlugin : public ILLMPlugin {
public:
MyLLMPlugin();
~MyLLMPlugin() override;
// Implement required interface methods
bool loadModel(const std::string& model_path, const json& config) override;
void unloadModel() override;
std::optional<ModelInfo> getModelInfo() const override;
bool isModelLoaded() const override;
bool loadLoRA(const std::string& lora_id, const std::string& lora_path, float scale) override;
bool unloadLoRA(const std::string& lora_id) override;
std::vector<LoRAInfo> listLoRAs() const override;
InferenceResponse generate(const InferenceRequest& request) override;
InferenceResponse generateRAG(const RAGContext& rag_context, const InferenceRequest& request) override;
std::vector<float> embed(const std::string& text) override;
LLMCapabilities getCapabilities() const override;
json getMemoryStats() const override;
json getPerformanceStats() const override;
std::vector<uint8_t> exportLoRA(const std::string& lora_id) override;
bool importLoRA(const std::string& lora_id, const std::vector<uint8_t>& data) override;
private:
// Your implementation details
};
} // namespace llm
} // namespace themisbool MyLLMPlugin::loadModel(const std::string& model_path, const json& config) {
// 1. Validate model path
if (!std::filesystem::exists(model_path)) {
spdlog::error("Model file not found: {}", model_path);
return false;
}
// 2. Load your model (using your backend)
// Example: my_model_ = your_backend::load_model(model_path);
// 3. Configure GPU offloading if supported
if (config.contains("n_gpu_layers")) {
// Configure GPU layers
}
// 4. Populate ModelInfo
model_info_.name = "my-model-7b";
model_info_.path = model_path;
model_info_.architecture = "llama";
model_info_.parameter_count = 7000000000; // 7B
model_info_.context_length = 4096;
model_info_.vram_required_mb = 4096;
model_loaded_ = true;
spdlog::info("Model loaded: {}", model_path);
return true;
}InferenceResponse MyLLMPlugin::generate(const InferenceRequest& request) {
if (!model_loaded_) {
throw std::runtime_error("No model loaded");
}
auto start = std::chrono::high_resolution_clock::now();
// 1. Tokenize prompt
// auto tokens = tokenize(request.prompt);
// 2. Apply LoRA if requested
if (request.lora_adapter_id) {
// Apply LoRA adapter
}
// 3. Generate tokens
// std::string generated_text = your_backend::generate(tokens, request.max_tokens);
// 4. Build response
InferenceResponse response;
response.text = generated_text;
response.model_used = model_info_.name;
response.tokens_generated = count_tokens(generated_text);
auto end = std::chrono::high_resolution_clock::now();
response.inference_time_ms =
std::chrono::duration<float, std::milli>(end - start).count();
response.tokens_per_second =
response.tokens_generated / (response.inference_time_ms / 1000.0f);
return response;
}InferenceResponse MyLLMPlugin::generateRAG(
const RAGContext& rag_context,
const InferenceRequest& request
) {
// 1. Format context with retrieved documents
std::ostringstream prompt;
prompt << "Context:\n";
for (const auto& doc : rag_context.documents) {
prompt << doc.content << "\n\n";
}
prompt << "Question: " << rag_context.query << "\n";
prompt << "Answer:";
// 2. Create modified request
InferenceRequest rag_request = request;
rag_request.prompt = prompt.str();
// 3. Generate with context
auto response = generate(rag_request);
// 4. Add RAG metadata
response.metadata["rag_enabled"] = true;
response.metadata["num_documents"] = rag_context.documents.size();
return response;
}// In your application startup code
#include "llm/llm_plugin_manager.h"
#include "my_llm_plugin.h"
void initializeLLM() {
auto plugin = std::make_unique<MyLLMPlugin>();
// Load model
json config = {
{"n_gpu_layers", 32},
{"n_ctx", 4096}
};
plugin->loadModel("/path/to/model.gguf", config);
// Register with manager
LLMPluginManager::instance().registerPlugin("my_llm", std::move(plugin));
}Load a model from disk.
Parameters:
-
model_path: Path to model file (e.g., .gguf, .safetensors) -
config: JSON configuration object
Common config options:
{
"n_gpu_layers": 32, // GPU offload layers
"n_ctx": 4096, // Context window size
"n_batch": 512, // Batch size
"n_threads": 8, // CPU threads
"max_vram_mb": 14336, // VRAM limit
"use_mmap": true // Memory-map model file
}Returns: true if successful
Unload current model and free resources.
Get information about the loaded model.
Returns: std::optional<ModelInfo> containing:
struct ModelInfo {
std::string name; // "mistral-7b-instruct"
std::string path; // "/models/mistral-7b.gguf"
std::string format; // "gguf"
std::string architecture; // "llama", "mistral", "gpt"
size_t parameter_count; // 7000000000 (7B)
size_t context_length; // 4096
size_t vram_required_mb; // 4096
};Load a LoRA adapter.
Parameters:
-
lora_id: Unique identifier for this adapter -
lora_path: Path to LoRA weights file -
scale: LoRA scaling factor (default: 1.0)
Example:
plugin->loadLoRA("legal-qa-v1", "/loras/legal-qa.bin", 1.0f);Unload a LoRA adapter from memory.
List all loaded LoRA adapters.
Returns: std::vector<LoRAInfo>
Generate text from a prompt.
Request structure:
InferenceRequest request;
request.prompt = "What is ThemisDB?";
request.max_tokens = 512;
request.temperature = 0.7f;
request.top_p = 0.9f;
request.lora_adapter_id = "legal-qa-v1"; // OptionalResponse structure:
InferenceResponse {
std::string text; // Generated text
int tokens_generated; // Number of tokens
float inference_time_ms; // Latency
float tokens_per_second; // Throughput
std::string model_used; // Model name
std::optional<std::string> lora_used;
};Generate with retrieved document context.
RAG Context:
RAGContext context;
context.query = "What are the legal requirements?";
context.documents = {
{.content = "Document 1...", .source = "doc1.pdf", .relevance_score = 0.95},
{.content = "Document 2...", .source = "doc2.pdf", .relevance_score = 0.87}
};Generate vector embedding for text.
Returns: std::vector<float> (typically 768 or 1024 dimensions)
Report plugin capabilities.
Example:
LLMCapabilities MyLLMPlugin::getCapabilities() const {
LLMCapabilities caps;
caps.supports_instruct = true;
caps.supports_lora = true;
caps.supports_streaming = true;
caps.gpu_accelerated = true;
caps.supports_cuda = true;
return caps;
}Get current memory usage.
Example return:
{
"vram_model_mb": 4096,
"vram_lora_mb": 128,
"vram_total_mb": 4224,
"lora_cache_size": 3
}Get performance metrics.
Example return:
{
"total_inferences": 1250,
"total_tokens_generated": 125000,
"avg_inference_time_ms": 287.5,
"avg_tokens_per_inference": 100,
"cache_hit_rate": 0.73
}For multi-shard deployments (see AI_ECOSYSTEM_SHARDING_ARCHITECTURE.md):
// Export LoRA for transfer to another shard
std::vector<uint8_t> MyLLMPlugin::exportLoRA(const std::string& lora_id) {
// Serialize LoRA weights to binary format
// Include metadata: version, checksum, etc.
std::vector<uint8_t> data;
// ... serialize your LoRA ...
return data;
}
// Import LoRA from another shard
bool MyLLMPlugin::importLoRA(
const std::string& lora_id,
const std::vector<uint8_t>& data
) {
// Deserialize and load LoRA weights
// Verify checksum
// Load into memory
return true;
}For token-by-token streaming:
InferenceRequest request;
request.prompt = "Tell me a story";
request.stream_callback = [](const std::string& token) {
std::cout << token << std::flush;
};
plugin->generate(request);For maximum performance with GPU-resident vector data:
// If your plugin supports zero-copy (CUDA Unified Memory)
LLMCapabilities caps = plugin->getCapabilities();
if (caps.supports_zero_copy) {
// Pass GPU pointers directly to plugin
// No CPU-GPU copies needed
}{
"name": "my-llm-plugin",
"version": "1.0.0",
"description": "My custom LLM backend for ThemisDB",
"type": "LLM",
"author": "Your Name",
"binary_linux": "libthemis_llm_myplugin.so",
"binary_windows": "themis_llm_myplugin.dll",
"binary_macos": "libthemis_llm_myplugin.dylib",
"capabilities": {
"supports_lora": true,
"supports_streaming": true,
"gpu_accelerated": true
},
"config_schema": {
"type": "object",
"properties": {
"model_path": {"type": "string"},
"n_gpu_layers": {"type": "integer", "default": 32},
"n_ctx": {"type": "integer", "default": 4096}
},
"required": ["model_path"]
}
}cmake_minimum_required(VERSION 3.20)
project(themis_llm_myplugin)
add_library(themis_llm_myplugin SHARED
my_llm_plugin.cpp
)
target_link_libraries(themis_llm_myplugin PRIVATE
themis_core
nlohmann_json::nlohmann_json
spdlog::spdlog
# Your backend dependencies
)
target_include_directories(themis_llm_myplugin PRIVATE
${CMAKE_SOURCE_DIR}/include
)
install(TARGETS themis_llm_myplugin
LIBRARY DESTINATION lib/themis/plugins
RUNTIME DESTINATION bin/themis/plugins
)#include <gtest/gtest.h>
#include "my_llm_plugin.h"
TEST(MyLLMPluginTest, LoadModel) {
MyLLMPlugin plugin;
bool loaded = plugin.loadModel("/path/to/test/model.gguf");
EXPECT_TRUE(loaded);
EXPECT_TRUE(plugin.isModelLoaded());
auto info = plugin.getModelInfo();
ASSERT_TRUE(info.has_value());
EXPECT_EQ(info->format, "gguf");
}
TEST(MyLLMPluginTest, BasicInference) {
MyLLMPlugin plugin;
plugin.loadModel("/path/to/test/model.gguf");
InferenceRequest request;
request.prompt = "Test prompt";
request.max_tokens = 10;
auto response = plugin.generate(request);
EXPECT_FALSE(response.text.empty());
EXPECT_GT(response.tokens_generated, 0);
}See:
-
Reference Implementation:
src/llm/llamacpp_plugin.cpp -
Architecture Design:
docs/llm/AI_ECOSYSTEM_SHARDING_ARCHITECTURE.md -
LLM Integration Guide:
docs/llm/NATIVE_LLM_INTEGRATION_CONCEPT.md
For questions or issues:
- Check the LLM Documentation
- Review the Architecture Document
- Open an issue on GitHub
Last Updated: December 2025
ThemisDB Version: v1.3.0
Status: Active Development
ThemisDB 1.9.0-beta Β· Home Β· Wiki-Index Β· Module-Index Β· FAQ Β· Quick-Reference Β· GitHub Β· Issues Β· Discussions Β· License
- Batch Operations
- Best Practices
- CRUD Tutorial
- Custom Document Ingestion
- Getting Started Tutorial
- Interactive Examples
- Schema Design
- Video Tutorials
- AQL Reference
- AQL Examples
- AQL Overview
- AQL Feature Roadmap
- AQL Geospatial Guide
- AQL LLM Migration Guide
- AQL API
- AQL Grammar (EBNF)
- AQL Root Overview
- AQL Examples (root)
- API Reference
- API Module README
- OpenAPI Overview
- Client SDK Overview
- SDK Overview
- Operations
- Operations Overview
- Operations Runbook
- Operations Handbook
- ThemisCtl Admin Guide
- Pipeline E2E SOPs
- Deploy Overview
- Docker Overview
- Docker Hub README
- Helm Overview
- Packaging Overview
- Operator Overview
- Security Policy
- Production Hardening Checklist
- Security Hardening Guide
- Encryption Key Management
- Access Control Framework
- Zero Trust Policy
- API Authentication & Authorization
- HSM Production Setup
- PKCS11 Integration
- DSGVO / SOC2 Checklist
- Access Model Runbooks
- Access Model Dashboard
- Maturity Automation Runbook
- Access Review Automation
- Access Model Dashboard
- Access Model Runbooks
- Rights Revocation
- Dr Checklists
- Dr Testing
- Incident Response Playbook
- Incident Response Testing
- GPU Oom Recovery
- Grammar Debugging
- Metrics Scrape Troubleshooting
- Model Swap Procedure
- Quota Tuning
- Subagent Deployment
- Logging Configuration
- Content Model
- Crypto & Keys
- Feature Flags Reference
- Modular Architecture Roadmap
- Modularization Guide
- Module Architecture Index
- PostgreSQL Wire Protocol
- Query Scheduling
- Raft Consensus Design
- Resource Pooling
- Source Directory Guide
- Unified Access Model
- E1 001 Layered Retrieval Design
- E1 002 Ann Abstraction Strategy
- E1 003 Tensor Summary Types
- E1 004 Lora Package Distinction
- E1 005 Model Switch Compatibility
- E1 006 Federated Tensor Summaries
- E2 001 Evaluation Framework Design
- E2 002 Hardware Profile Strategy
- E2 003 Query Planner Routing Model
- E2 004 Approximation Governance Rules
- E2 005 Cross Layer Fallback Confidence Policy
- E3 001 Distributed Tensor Design
- E3 002 Manifest Coordination Strategy
- E3 003 Recovery And Erasure Choice
- E3 004 Tensor Fabric Infrastructure
- Contributing
- Contributing (root)
- Code of Conduct
- Support
- Maintainers
- CTest Guide
- Build Quick Reference
- Developer Wiki Index
- Build / Test / CI
- Module Index
- Branching Strategy
- Disabled Stub Policy
- Docs PR Policy
- GA Promotion Sign Off
- Github Milestones Setup
- Maturity Claim Verification Checklist
- Maturity Evidence Registry
- Merge Gate Bot Config
- Merge Gate Status Live
- Phase 1 Closure Report
- Phase Closure Policy
- Phase Dependency Graph
- Phase3 Enforcement Runbook
- Plugin Submodule Rollback
- PR Version Targeting
- PR Version Targeting Backfill
- Production Ready 2026 Delivery Plan
- Query Module Status
- Readme
- Release Promotion Gate Policy
- Release Validation Checklist
- Security Module 5671 Evidence Summary
- Sharding P6 Residual Risk Acceptance
- Sourcecode Compliance Governance
- Updates Development Status Sign Off
- Wave C Implementation Complete
- Blob Storage
- Cuda
- Ethics Ai
- Exporters
- Huggingface
- Image Analysis
- Importers
- RPC
- Scraper
- Themisdb Ai Watermark Detector
- User Storage Encrypted
- Chimera Architecture
- Chimera Future
- Chimera Readme
- Chimera Roadmap
- Covina Fastapi Ingestion Architecture
- Covina Fastapi Ingestion Future
- Covina Fastapi Ingestion Roadmap
- Vcc Base Architecture
- Vcc Base Future
- Vcc Base Roadmap
- Vcc Clara Ingestion Architecture
- Vcc Clara Ingestion Future
- Vcc Clara Ingestion Roadmap
- Vcc Veritas Architecture
- Vcc Veritas Future
- Vcc Veritas Roadmap
- 01 Hello World
- 02 Todo App
- 03 Contact Manager
- 04 Inventory System
- 05 Time Series Monitor
- 06 Graph Social Network
- 07 Vector Search Documents
- 08 Dms Erp System
- 09 Iot Sensor Network
- 10 Drone Image Analysis
- 11 Blog Wiki
- 12 Expense Tracker
- 13 Recipe Manager
- 14 Ecommerce Catalog
- 15 Event Management
- 16 Kanban Board
- 17 Crm
- 18 Realtime Chat
- 19 Recommendation Engine
- 20 Smart Home
- 21 Coding Platform
- 22 AQL Diagram Tool
- 23 Traveling Salesman
- 24 Moral Philosophy Debates
- API Versioning
- Distributed Sharding
- Feedback Plugins
- Geo
- Gnn
- Image Analysis
- Legal Lora Training
- LLM
- Lora Sync
- Migration
- Nlp
- Performance
- Railway
- Replication
- Rope Visualization
- Sample Product Config
- Security
- Client SDK Overview
- Quickstart
- Sdk Enhancements
- Sdk Implementation Summary
- Test Suite Readme
- Go
- Java
- Javascript
- Php
- Python
- Ruby
- Rust
- Typescript
- 01 Grundlegende Operationen
- 02 AQL Queries
- 03 Graph Daten
- 04 Multimodell Anwendung
- 01 Quickstart Guide
- 02 AQL Referenz Kurzuebersicht
- 03 Datenmodellierung Guide
- 04 Uebungsaufgaben
- 05 Best Practices Guide
- Training Documents
- Training Overview
- 01 Einfuehrung Und Uebersicht
- 02 Datenmodelle Und Architektur
- 03 AQL Abfragesprache
- 04 Installation Und Setup
- 05 Anwendungsbeispiele
- Training Presentations
- Dependencies Readme
- Processmonitor Readme
- Themis.admintools.shared Readme
- Themis.aqlquerybuilder Readme
- Themis.aqlquerybuilder Roadmap
- Themis.auditlogviewer Readme
- Themis.auditlogviewer Roadmap
- Themis.classificationdashboard Readme
- Themis.classificationdashboard Roadmap
- Themis.compliancereports Readme
- Themis.compliancereports Roadmap
- Themis.gisviewer.controlpanel Readme
- Themis.gisviewer.controlpanel Roadmap
- Themis.impactanalysisviewer Readme
- Themis.impactanalysisviewer Roadmap
- Themis.ingestiontool Readme
- Themis.ingestiontool Roadmap
- Themis.keyrotationdashboard Readme
- Themis.keyrotationdashboard Roadmap
- Themis.piimanager Readme
- Themis.piimanager Roadmap
- Themis.retentionmanager Readme
- Themis.retentionmanager Roadmap
- Themis.sagaverifier Readme
- Themis.sagaverifier Roadmap
- Themis.usbadmintool Readme
- Themis.usbadmintool Roadmap
- CI Readme
- CI Roadmap
- Compiler Diagnostics Readme
- Compiler Diagnostics Roadmap
- Completion Readme
- Copilot Ollama Router Readme
- Copilot Ollama Router Roadmap
- Gnn Readme
- Gnn Roadmap
- Rope Visualizer Readme
- Rope Visualizer Roadmap
- Tco Calculator Readme
- Tco Calculator Roadmap
- Tests Readme
- Tests Roadmap
- Themis Config Wx Readme
- Themis Docs Builder Readme
- Wikipedia Ingestion Readme