Your First Agent - Basic Chat
Prerequisites
Step 1: Create Your Script
Step 2: Write the Code
import * as dotenv from 'dotenv';
dotenv.config(); // Load environment variables
import { AgentB, LLMMessage } from '@ulifeai/agentb';
import readline from 'readline/promises'; // For console input
async function runBasicChat() {
// 1. Initialize AgentB
// This sets up the LLM client (OpenAI by default if OPENAI_API_KEY is set)
// and default in-memory storage for conversations.
AgentB.initialize({
llmProvider: {
provider: 'openai',
model: 'gpt-4o-mini', // Feel free to change the model
},
// No tools needed for this basic chat
});
console.log("๐ค AgentB Initialized for Basic Chat!");
// 2. Set up for console interaction
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const threadId = `basic-chat-thread-${Date.now()}`; // A unique ID for this conversation
console.log(`\nStarting chat on thread: ${threadId}`);
console.log("Type 'exit' to end the chat.\n");
// 3. Chat Loop
while (true) {
const userInput = await rl.question("You: ");
if (userInput.toLowerCase() === 'exit') {
break;
}
if (!userInput.trim()) {
continue;
}
const userMessage: LLMMessage = { role: 'user', content: userInput };
process.stdout.write("Agent: ");
try {
// 4. Get the agent's response stream
const agentEventStream = AgentB.runHttpInteractionStream(
threadId,
userMessage
// No specific AgentRunConfig override needed for this simple case
);
// 5. Process the stream of events
for await (const event of agentEventStream) {
if (event.type === 'thread.message.delta' && event.data.delta.contentChunk) {
// Stream content chunks to the console
process.stdout.write(event.data.delta.contentChunk);
}
if (event.type === 'thread.message.completed' && event.data.message.role === 'assistant') {
// Newline after the assistant's full message is completed
process.stdout.write("\n");
}
if (event.type === 'thread.run.failed') {
process.stdout.write("\n");
console.error("๐ Agent run failed:", event.data.error.message);
break; // Exit the event loop for this turn on failure
}
// You can log other event types for debugging if you like:
// else if (event.type !== 'thread.message.delta') {
// console.log(`\n[Event: ${event.type}]`);
// }
}
} catch (error) {
console.error("\n๐ Error during agent interaction:", error);
}
process.stdout.write("\n");
}
console.log("\n๐ Chat ended. Goodbye!");
rl.close();
}
runBasicChat().catch(console.error);Step 3: Run Your Agent
Key Takeaways
Last updated