import { Chat, Memory } from 'nebula-sdk';
class ContextualChat {
private chat: Chat;
private memory: Memory;
private sessionId: string;
constructor(apiKey: string, sessionId: string) {
this.chat = new Chat({ apiKey });
this.memory = new Memory({
storageKey: `chat_memory_${sessionId}`,
apiKey
});
this.sessionId = sessionId;
}
async sendMessage(message: string) {
// Retrieve relevant context
const context = await this.getRelevantContext(message);
// Send message with context
const response = await this.chat.send({
message,
context: context.messages,
systemPrompt: `You are a helpful assistant. Use the following context to provide relevant responses:
User preferences: ${JSON.stringify(context.preferences)}
Previous topics: ${context.topics.join(', ')}`
});
// Store the conversation
await this.storeConversation(message, response.content);
return response;
}
private async getRelevantContext(message: string) {
// Get user preferences
const preferences = await this.memory.retrieve(`preferences:${this.sessionId}`);
// Get recent conversation history
const recentMessages = await this.memory.search({
tags: ['conversation', this.sessionId],
sortBy: 'timestamp',
sortOrder: 'desc',
limit: 10
});
// Get relevant knowledge
const relevantKnowledge = await this.memory.search({
text: message,
tags: ['knowledge'],
limit: 5
});
return {
preferences: preferences?.value || {},
messages: recentMessages.results.map(r => r.value),
topics: relevantKnowledge.results.map(r => r.value.topic),
knowledge: relevantKnowledge.results.map(r => r.value.content)
};
}
private async storeConversation(userMessage: string, assistantResponse: string) {
const timestamp = new Date();
// Store user message
await this.memory.store({
key: `msg_user_${timestamp.getTime()}`,
value: {
role: 'user',
content: userMessage,
timestamp
},
tags: ['conversation', this.sessionId, 'user']
});
// Store assistant response
await this.memory.store({
key: `msg_assistant_${timestamp.getTime() + 1}`,
value: {
role: 'assistant',
content: assistantResponse,
timestamp: new Date(timestamp.getTime() + 1)
},
tags: ['conversation', this.sessionId, 'assistant']
});
}
}