import { use } from '@memvid/sdk';
import OpenAI from 'openai';
// Get Memvid functions
const mem = await use('autogen', 'knowledge.mv2');
const functions = mem.functions;
const client = new OpenAI();
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'system', content: 'You are a helpful research assistant with access to a knowledge base.' },
{ role: 'user', content: 'Find information about authentication and summarize it.' },
];
// Execute function by name
async function executeFunction(name: string, args: any): Promise<string> {
if (name === 'memvid_find') {
const result = await mem.find(args.query, { k: args.top_k || 5 });
return JSON.stringify(result.hits?.map((h: any) => ({
title: h.title,
snippet: h.snippet || h.text?.slice(0, 200),
score: h.score,
})));
} else if (name === 'memvid_ask') {
const result = await mem.ask(args.question, { mode: args.mode || 'auto' });
return result.answer || 'No answer generated';
} else if (name === 'memvid_put') {
const frameId = await mem.put({
title: args.title,
label: args.label,
text: args.text,
});
return `Document stored with frame_id: ${frameId}`;
}
return 'Unknown function';
}
// Conversation loop
while (true) {
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages,
tools: functions.map((f: any) => ({ type: 'function' as const, function: f })),
tool_choice: 'auto',
});
const message = response.choices[0].message;
messages.push(message);
if (message.tool_calls) {
for (const toolCall of message.tool_calls) {
const funcName = toolCall.function.name;
const funcArgs = JSON.parse(toolCall.function.arguments);
const result = await executeFunction(funcName, funcArgs);
messages.push({
role: 'tool',
tool_call_id: toolCall.id,
content: result,
});
}
} else {
console.log('Assistant:', message.content);
break;
}
}
await mem.seal();