Method Serialize
Serialize()
Serializes the memory to a byte array.
public byte[] Serialize()
Returns
- byte[]
A byte array containing the serialized memory data.
Examples
Example: Serializing to a byte array
using LMKit.Agents;
using LMKit.Model;
using var embeddingModel = new LM("path/to/embedding-model.gguf");
var memory = new AgentMemory(embeddingModel);
// Store some information
await memory.SaveInformationAsync("test", "Sample data.", "sample_001");
// Serialize to bytes
byte[] data = memory.Serialize();
Console.WriteLine($"Serialized memory size: {data.Length} bytes");
// Later, deserialize
var loadedMemory = AgentMemory.Deserialize(data, embeddingModel);
Console.WriteLine($"Loaded {loadedMemory.DataSources.Count} data source(s).");
Remarks
This method is useful for storing memory in databases or transmitting over networks. Use Deserialize(byte[], LM) to reconstruct the memory from the byte array.
Serialize(string)
Serializes the memory to a file at the specified path.
public void Serialize(string path)
Parameters
pathstringThe file path where the serialized data will be written.
Examples
Example: Persisting memory to disk
using LMKit.Agents;
using LMKit.Model;
using var embeddingModel = new LM("path/to/embedding-model.gguf");
var memory = new AgentMemory(embeddingModel);
// Build up memory during session
await memory.SaveInformationAsync("session", "User asked about billing.", "query_001");
await memory.SaveInformationAsync("session", "User upgraded to premium.", "action_001");
// Save before application closes
string savePath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), "MyApp", "memory.bin");
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
memory.Serialize(savePath);
Console.WriteLine($"Memory saved to: {savePath}");
Remarks
If a file already exists at the specified path, it will be overwritten. The file format is binary and specific to LM-Kit; use Deserialize(string, LM) to load it.
Exceptions
- ArgumentNullException
Thrown when
pathis null or empty.- IOException
Thrown when an I/O error occurs during writing.
Serialize(Stream)
Serializes the memory to the specified stream.
public void Serialize(Stream stream)
Parameters
streamStreamA writable stream to write the serialized data to.
Remarks
The stream is left open after serialization. The caller is responsible for disposing the stream.
Exceptions
- ArgumentNullException
Thrown when
streamisnull.- ArgumentException
Thrown when
streamis not writable.