Context Handling Guide
This guide explains how to effectively manage context in your memories using the Papr Memory API. Context helps create richer, more meaningful memories that are easier to retrieve and understand.
Understanding Context
In Papr Memory, context can be added in several ways:
- Conversation Context: Dialog history that led to the memory
- Metadata Context: Additional information about the memory
- Hierarchical Context: Organizational structure of memories
- Emotional Context: Sentiment and emotional indicators
Conversation Context
When storing memories from conversations, include relevant dialog:
const memory = {
content: "Decision to implement new feature based on user feedback",
type: "text",
context: [
{
role: "user",
content: "Our users are requesting a dark mode feature"
},
{
role: "assistant",
content: "I understand. How high priority is this feature?"
},
{
role: "user",
content: "Very high. Users are having eye strain issues."
}
],
metadata: {
topics: ["feature request", "user feedback", "accessibility"],
hierarchical_structures: "Product/Features/UI/DarkMode",
external_user_id: "user_123"
}
};
const response = await fetch('https://memory.papr.ai/v1/memory', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': '<your-api-key>',
'Accept-Encoding': 'gzip',
'X-Client-Type': 'custom_app'
},
body: JSON.stringify(memory)
});
Metadata Context
Use metadata to add rich contextual information:
const memory = {
content: "Quarterly planning meeting outcomes",
type: "text",
metadata: {
topics: ["planning", "strategy", "objectives"],
hierarchical_structures: "Business/Planning/Quarterly",
createdAt: new Date().toISOString(),
location: "Conference Room A",
emoji_tags: ["📊", "🎯", "📅"],
emotion_tags: ["focused", "optimistic", "determined"],
conversationId: "q2-planning-2024",
sourceUrl: "https://meetings.company.com/q2-planning",
external_user_id: "user_123"
}
};
Hierarchical Context
Create meaningful navigation paths:
// Helper function to build hierarchical paths
function buildHierarchy(categories: string[]): string {
return categories.join('/');
}
const memory = {
content: "New feature specification",
type: "text",
metadata: {
hierarchical_structures: buildHierarchy([
"Product",
"Development",
"Features",
"DarkMode"
]),
topics: ["feature specification", "development", "UI"],
external_user_id: "user_123"
}
};
Emotional Context
Add emotional context to improve retrieval relevance:
// Helper function to analyze and tag emotions
function addEmotionalContext(content: string, metadata: any) {
// Your emotion analysis logic here
return {
...metadata,
emotion_tags: ["determined", "excited"], // Example tags as array
emoji_tags: ["💪", "✨", "🎯"] // Relevant emojis as array
};
}
const memory = {
content: "Team successfully launched new feature ahead of schedule",
type: "text",
metadata: addEmotionalContext(content, {
topics: ["launch", "milestone", "achievement"],
hierarchical_structures: "Projects/Features/Launch",
external_user_id: "user_123"
})
};
Linking Related Memories
Connect related memories using conversation IDs and metadata:
// Create a thread of related memories
async function createMemoryThread(memories: Memory[], threadId: string, externalUserId: string) {
const batchResponse = await fetch('https://memory.papr.ai/v1/memory/batch', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': '<your-api-key>',
'Accept-Encoding': 'gzip',
'X-Client-Type': 'custom_app'
},
body: JSON.stringify({
memories: memories.map(memory => ({
...memory,
metadata: {
...memory.metadata,
conversationId: threadId,
createdAt: new Date().toISOString(),
external_user_id: externalUserId
}
})),
external_user_id: externalUserId,
batch_size: 10
})
});
return response.json();
}
// Example usage
const threadId = 'feature-123-discussion';
const externalUserId = 'user_123';
const memories = [
{
content: "Initial feature discussion",
type: "text",
metadata: {
topics: ["feature planning"],
hierarchical_structures: "Product/Features/Planning"
}
},
{
content: "Technical requirements defined",
type: "text",
metadata: {
topics: ["technical specs"],
hierarchical_structures: "Product/Features/Technical"
}
},
{
content: "Implementation timeline agreed",
type: "text",
metadata: {
topics: ["timeline", "planning"],
hierarchical_structures: "Product/Features/Timeline"
}
}
];
await createMemoryThread(memories, threadId, externalUserId);
Relationships Between Memories
Define explicit relationships between memories:
// Define a relationship between two memories
const memory = {
content: "Follow-up to our previous discussion about the feature timeline",
type: "text",
metadata: {
topics: ["feature", "timeline", "planning"],
external_user_id: "user_123",
conversationId: "feature-123-planning"
},
relationships_json: [
{
relation_type: "follows",
related_item_id: "mem_abc123", // ID of related memory
metadata: {
relevance: "high"
}
}
]
};
Context-Aware Search
Leverage context in your search queries:
async function contextualSearch(
topic: string,
context: {
project?: string;
timeframe?: string;
user?: string;
}
): Promise<SearchResult> {
// Build a detailed query using context
let queryText = `Find information about ${topic}`;
if (context.project) {
queryText += ` related to the ${context.project} project`;
}
if (context.timeframe) {
queryText += ` from ${context.timeframe}`;
}
if (context.user) {
queryText += ` involving ${context.user}`;
}
// Search with enhanced query and agentic graph enabled
const response = await fetch('https://memory.papr.ai/v1/memory/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': '<your-api-key>',
'X-Client-Type': 'custom_app',
'Accept-Encoding': 'gzip'
},
body: JSON.stringify({
query: queryText,
enable_agentic_graph: true, // Enable intelligent entity-aware search
max_memories: 20,
max_nodes: 15
})
});
return response.json();
}
// Example usage
const results = await contextualSearch('API implementation', {
project: 'Authentication Service',
timeframe: 'last two weeks',
user: 'Alex'
});
Providing Search Feedback
Improve future search results by providing feedback:
async function provideFeedback(
searchId: string,
isHelpful: boolean,
comments?: string
): Promise<any> {
const response = await fetch('https://memory.papr.ai/v1/feedback', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': '<your-api-key>',
'X-Client-Type': 'custom_app'
},
body: JSON.stringify({
search_id: searchId,
feedbackData: {
feedbackType: isHelpful ? 'thumbs_up' : 'thumbs_down',
feedbackSource: 'inline',
feedbackText: comments
}
})
});
return response.json();
}
// Example usage after receiving search results
const searchResponse = await contextualSearch('API implementation', { project: 'Authentication Service' });
const searchId = searchResponse.search_id;
// Later, after reviewing results
await provideFeedback(searchId, true, "These results contained exactly the API implementation details I needed");
Best Practices for Context Handling
- Include conversation history: Add previous messages for better context understanding
- Use comprehensive metadata: Provide detailed metadata including topics, hierarchies, and emotional context
- Build meaningful hierarchies: Create logical navigation paths with hierarchical_structures
- Link related memories: Use conversationId and relationships to connect related content
- Use external_user_id consistently: Ensure memories from the same user are properly linked
- Include timestamps: Add createdAt and other temporal information for better context
- Add emotional indicators: Include emotion_tags and emoji_tags for richer understanding
Next Steps
- Learn about Batch Operations
- Explore Search Tuning for more advanced search techniques
- See the complete API Reference