Create an email processing workflow

This example demonstrates how to create a workflow that analyzes an email and generates a response when needed.


Email Processing Workflow Example

Email Processing Workflow Example

import "dotenv/config";
import { Langbase, Workflow } from "langbase";

async function processEmail({ emailContent }: { emailContent: string }) {
  // Initialize Langbase
  const langbase = new Langbase({
    apiKey: process.env.LANGBASE_API_KEY!,
  });

  // Create a new workflow
  const workflow = new Workflow();

  try {
    // Steps 1 & 2: Run summary and sentiment analysis in parallel
    const [summary, sentiment] = await Promise.all([
      workflow.step({
        id: "summarize_email", // The id for the step
        run: async () => {
          const response = await langbase.agent.run({
            model: "openai:gpt-4.1-mini",
            instructions: `Create a concise summary of this email. Focus on the main points,
          requests, and any action items mentioned.`,
            apiKey: process.env.LLM_API_KEY!,
            input: [{ role: "user", content: emailContent }],
            stream: false,
          });

          return response.output;
        },
      }),

      workflow.step({
        id: "analyze_sentiment",
        run: async () => {
          const response = await langbase.agent.run({
            model: "openai:gpt-4.1-mini",
            instructions: `Analyze the sentiment of this email. Provide a brief analysis
            that includes the overall tone (positive, neutral, or negative) and any notable
            emotional elements.`,
            apiKey: process.env.LLM_API_KEY!,
            input: [{ role: "user", content: emailContent }],
            stream: false,
          });

          return response.output;
        },
      }),
    ]);

    // Step 3: Determine if response is needed (using the results from previous steps)
    const responseNeeded = await workflow.step({
      id: "determine_response_needed",
      run: async () => {
        const response = await langbase.agent.run({
          model: "openai:gpt-4.1-mini",
          instructions: `Based on the email summary and sentiment analysis, determine if a
          response is needed. Answer with 'yes' if a response is required, or 'no' if no
          response is needed. Consider factors like: Does the email contain a question?
          Is there an explicit request? Is it urgent?`,
          apiKey: process.env.LLM_API_KEY!,
          input: [
            {
              role: "user",
              content: `Email: ${emailContent}\n\nSummary: ${summary}\n\nSentiment: ${sentiment}\n\nDoes this email
              require a response?`,
            },
          ],
          stream: false,
        });

        return response.output.toLowerCase().includes("yes");
      },
    });

    // Step 4: Generate response if needed
    let response = null;
    if (responseNeeded) {
      response = await workflow.step({
        id: "generate_response",
        run: async () => {
          const response = await langbase.agent.run({
            model: "openai:gpt-4.1-mini",
            instructions: `Generate a professional email response. Address all questions
            and requests from the original email. Be helpful, clear, and maintain a
            professional tone that matches the original email sentiment.`,
            apiKey: process.env.LLM_API_KEY!,
            input: [
              {
                role: "user",
                content: `Original Email: ${emailContent}\n\nSummary: ${summary}\n\n
                Sentiment Analysis: ${sentiment}\n\nPlease draft a response email.`,
              },
            ],
            stream: false,
          });

          return response.output;
        },
      });
    }

    // Return the results
    return {
      summary,
      sentiment,
      responseNeeded,
      response,
    };
  } catch (error) {
    console.error("Email processing workflow failed:", error);
    throw error;
  }
}

async function main() {
  const sampleEmail = `
Subject: Pricing Information and Demo Request

    Hello,

    I came across your platform and I'm interested in learning more about your product
    for our growing company. Could you please send me some information on your pricing tiers?

    We're particularly interested in the enterprise tier as we now have a team of about
    50 people who would need access. Would it be possible to schedule a demo sometime next week?

    Thanks in advance for your help!

    Best regards,
    Jamie

`;

  const results = await processEmail({ emailContent: sampleEmail });
  console.log(JSON.stringify(results, null, 2));
}

main();