In AgentScope AI, agents are equipped with a sophisticated memory system that stores conversation history and contextual data. This memory system supports both traditional message storage and vector-based semantic search. It enables agents to maintain state across interactions, retrieve relevant historical context, and facilitate advanced security auditing tasks.
Memory Configuration
The memory system in AgentScope AI is highly configurable and supports multiple storage backends. Below is an example configuration that demonstrates how to set up memory using a PostgreSQL storage backend and vector-based semantic search.
typescript // File: src/memory/config.ts
import { Memory } from '@agentscope/memory';
import { PostgresStore } from '@agentscope/store-pg';
import { PgVector } from '@agentscope/vector-pg';
// Initialize memory with PostgreSQL storage and optional vector search
const memory = new Memory({
// Required: Storage backend for messages
storage: new PostgresStore({
host: 'localhost',
port: 5432,
user: 'postgres',
database: 'postgres',
password: 'postgres',
}),
// Optional: Vector store for semantic search
vector: new PgVector('your_connection_string_here'),
// Optional: Memory configuration options
options: {
// Number of recent messages to include in context (set false to disable)
lastMessages: 10,
// Configure vector-based semantic search
historySearch: {
topK: 3, // Number of semantic search results
messageRange: 2 // Number of messages before and after each result
},
},
// Required if using vector search: embedding options
embeddingOptions: {
provider: 'AgentScope AI',
model: 'text-embedding-ada-002',
maxRetries: 3,
},
});
export default memory;
When an AgentScope AI instance is initialized with this memory configuration, all agents automatically use these settings when calling their generate() or stream() methods. The options specified in the configuration are applied to all conversations unless overridden in specific calls.
Using Memory in Agents
Once configured, the memory system is automatically utilized by agents. This integration enables agents to store messages, create vector embeddings for semantic search, and inject relevant historical context into new conversations. The following example demonstrates how memory is used during agent interactions:
typescript // File: src/index.ts
import { AgentScope } from '@agentscope/core';
import memory from './memory/config';
import { securityAgent } from './agents';
const agentscope = new AgentScope({
agents: { securityAgent },
memory,
});
// Memory is automatically used in agent interactions
async function getAgentResponse() {
const response = await securityAgent.generate(
"What did we discuss earlier about security protocols?",
{
resourceId: "user_123",
threadId: "thread_456",
}
);
console.log("Agent Response:", response.text);
}
getAgentResponse();
Agents can also override the default memory settings for individual requests. For example:
typescript // Override memory settings for a specific call
const customResponse = await securityAgent.generate(
"Summarize our previous conversation on audit results.",
{
resourceId: "user_123",
threadId: "thread_456",
memoryOptions: {
lastMessages: 5, // Only include the 5 most recent messages
historySearch: {
topK: 2, // Retrieve 2 semantic search results
messageRange: {
before: 1,
after: 1
}
},
}
}
);
console.log("Custom Response:", customResponse.text);
Similarly, the stream() method can be used with custom memory options:
typescript
const stream = await securityAgent.stream("Detail the risk assessment from our previous audit", {
resourceId: "user_123",
threadId: "thread_456",
memoryOptions: {
lastMessages: 20 // Provide broader context for the conversation
}
});
for await (const chunk of stream.textStream) {
process.stdout.write(chunk);
}
Manual Thread Management
While the agent methods automatically handle thread management, you may manage threads manually for advanced use cases. This is useful when creating threads before starting conversations, managing thread metadata, or explicitly saving/retrieving messages.
typescript// File: src/memory/threadManagement.ts
import { Memory } from '@agentscope/memory';
import { PostgresStore } from '@agentscope/store-pg';
const memory = new Memory({
storage: new PostgresStore({
host: 'localhost',
port: 5432,
user: 'postgres',
database: 'postgres',
password: 'postgres',
})
});
// Create a new thread
async function createThread() {
const thread = await memory.createThread({
resourceId: "user_123",
title: "Security Audit Discussion",
metadata: {
project: "AgentScope AI",
topic: "memory management"
}
});
console.log("New Thread Created:", thread.id);
return thread.id;
}
// Save messages to a thread
async function saveThreadMessages(threadId: string) {
await memory.saveMessages({
messages: [{
id: "msg_1",
threadId: threadId,
role: "user",
content: "What vulnerabilities were detected in our last audit?",
createdAt: new Date(),
type: "text"
}]
});
}
// Retrieve messages from a thread
async function getThreadMessages(threadId: string) {
const messages = await memory.getMessages({
threadId: threadId,
selectBy: {
last: 10
}
});
console.log("Thread Messages:", messages);
}
export { createThread, saveThreadMessages, getThreadMessages };