Run Agent with Memory

This example demonstrates how to retrieve and attach memory to an agent call.


Run Agent with Memory Example

Run Agent with Memory Example

import 'dotenv/config';
import { Langbase } from 'langbase';

const langbase = new Langbase({
	apiKey: process.env.LANGBASE_API_KEY!,
});

async function main() {
	if (!process.env.LANGBASE_API_KEY) {
		console.error('❌ Missing LANGBASE_API_KEY in environment variables.');
		process.exit(1);
	}

	// Step 1: Retrieve memory
	const memoryResponse = await langbase.memories.retrieve({
		memory: [
			{
				name: 'career-advisor-memory',
			},
		],
		query: 'Who is an AI Engineer?',
		topK: 2,
	});

	// Step 2: Run the agent with the retrieved memory
	const { output } = await langbase.agent.run({
        model: 'openai:gpt-4.1-mini',
        apiKey: process.env.LLM_API_KEY!,
        instructions: 'You are a career advisor who helps users understand AI job roles.',
        input: [
            {
                role: 'user',
                content: `${memoryResponse}\n\n Now, based on the above, who is an AI Engineer?`,
            },
        ],
    });

	// Step 3: Display output
	console.log('Agent Response:', output);
}

main();