Run Agent with Tool

This example demonstrates how to run an agent that can call a tool — in this case, a function that sends an email using the Resend API.


Run Agent with Tool Example

Run Agent with Tool Example

import 'dotenv/config';
import { Langbase, Message, type Tools } from 'langbase';

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

// Define the tool schema for sending emails
const sendEmailToolSchema: Tools = {
    type: "function",
    function: {
        name: "send_email",
        description: "Send an email using Resend API",
        parameters: {
            type: "object",
            required: ["from", "to", "subject", "html", "text"],
            properties: Object.fromEntries(
                ["from", "to", "subject", "html", "text"].map((field) => [
                    field,
                    { type: "string" },
                ])
            ),
            additionalProperties: false,
        },
    },
};

// Actual tool function
async function send_email(args: any) {
    const { from, to, subject, html, text } = args;

    const response = await fetch('https://api.resend.com/emails', {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${process.env.RESEND_API_KEY}`,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            from,
            to,
            subject,
            html,
            text,
        }),
    });

    if (!response.ok) {
        throw new Error('Failed to send email');
    }

    const data = await response.json();
    return `✅ Email sent successfully to ${to}!`;
}

async function main() {
    if (!process.env.LANGBASE_API_KEY || !process.env.RESEND_API_KEY || !process.env.OPENAI_API_KEY) {
        console.error('❌ Missing required API keys.');
        process.exit(1);
    }

    const recipientInfo = {
        email: "sam@example.com",
    };

    const email = {
        subject: "Welcome to Langbase!",
        htmlEmail: "<h1>Hello Sam!</h1><p>Welcome to Langbase.</p>",
        fullEmail: "Hello Sam! Welcome to Langbase.",
    };

    const inputMessages: Message[] = [
        {
            role: 'user',
            content: 'Send a welcome email to Sam.',
        },
    ];

    // Initial run with tool
    const response = await langbase.agent.run({
        model: "openai:gpt-4.1-mini",
        apiKey: process.env.OPENAI_API_KEY!,
        instructions: "You are an email sending assistant.",
        input: inputMessages,
        tools: [sendEmailToolSchema],
        stream: false,
    });

    // Push agent tool call to messages
    inputMessages.push(response.choices[0].message);

    // Detect tool call
    const toolCalls = response.choices[0].message.tool_calls;
    const hasToolCalls = toolCalls && toolCalls.length > 0;

    if (hasToolCalls) {
        for (const toolCall of toolCalls) {
            // Process each tool call
            const { name, arguments: args } = toolCall.function;
            const parsedArgs = JSON.parse(args);

            parsedArgs.from = "onboarding@resend.dev";
            parsedArgs.to = recipientInfo.email;
            parsedArgs.subject = email.subject;
            parsedArgs.html = email.htmlEmail;
            parsedArgs.text = email.fullEmail;

            const result = await send_email(parsedArgs);

            inputMessages.push({
                role: 'tool',
                tool_call_id: toolCall.id,
                name,
                content: result,
            });
        }
    }

    // Final agent response with tool result
    const { output: finalOutput } = await langbase.agent.run({
        model: "openai:gpt-4.1-mini",
        apiKey: process.env.OPENAI_API_KEY!,
        instructions: `You are an email sending assistant.
            Confirm the email has been sent successfully.`,
        input: inputMessages,
        stream: false,
    });

    console.log('Final Output:', finalOutput);
}

main();