{"id":33760389,"url":"https://github.com/pguso/email-agent-core","last_synced_at":"2026-05-26T20:31:33.186Z","repository":{"id":326349777,"uuid":"1104640350","full_name":"pguso/email-agent-core","owner":"pguso","description":"A minimal, modular JavaScript toolkit focused on email automation with AI. Includes two ready-made agents, an Email Classifier and an Email Response Generator, plus a lightweight agent framework with Actions, Messages, Prompt Templates, JSON parsing, and unified LLM wrappers (OpenAI + Llama.cpp).","archived":false,"fork":false,"pushed_at":"2025-11-27T08:13:59.000Z","size":155,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-12-08T16:20:51.410Z","etag":null,"topics":["ai-agents","ai-agents-framework","email-classification","email-responder","imap","imap-client","llama-cpp","llm","openai"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pguso.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-11-26T13:38:19.000Z","updated_at":"2025-11-27T08:14:02.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/pguso/email-agent-core","commit_stats":null,"previous_names":["pguso/email-agent-core"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/pguso/email-agent-core","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pguso%2Femail-agent-core","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pguso%2Femail-agent-core/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pguso%2Femail-agent-core/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pguso%2Femail-agent-core/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pguso","download_url":"https://codeload.github.com/pguso/email-agent-core/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pguso%2Femail-agent-core/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33538659,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"ssl_error","status_checked_at":"2026-05-26T15:22:15.568Z","response_time":63,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-agents","ai-agents-framework","email-classification","email-responder","imap","imap-client","llama-cpp","llm","openai"],"created_at":"2025-12-05T10:02:01.009Z","updated_at":"2026-05-26T20:31:33.180Z","avatar_url":"https://github.com/pguso.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# E-Mail Agent\n\nA powerful, lightweight npm package for building intelligent email automation agents. This package provides a composable framework to fetch, parse, classify, and respond to emails using LLM models (both local and cloud-based).\n\n## Features\n\n- **IMAP Email Fetching**: Connect to any IMAP server and fetch emails programmatically\n- **Email Parsing**: Transform raw email data into clean, structured objects\n- **AI-Powered Classification**: Automatically classify emails by category, priority, sentiment, and more\n- **Smart Response Generation**: Generate contextual, professional email responses using LLM\n- **Composable Architecture**: Chain agents together to create complex workflows\n- **Multiple LLM Providers**: Support for both local models (`node-llama-cpp`) and cloud providers (OpenAI)\n- **TypeScript First**: Written in TypeScript with full type definitions\n\n\u003e If you want to dig deeper into how email-agent-core is build, what opportunities it offers and production ready examples read [TUTORIAL.md](TUTORIAL.md)\n\n## Installation\n\n```bash\nnpm install email-agent-core\n```\n\n## Quick Start\n\n### 1. Fetch Emails from IMAP\n\n```javascript\nimport { EmailImapClient } from 'email-agent-core';\n\nconst config = {\n  host: 'imap.gmail.com',\n  port: 993,\n  tls: true,\n  user: 'your-email@gmail.com',\n  pass: 'your-password'\n};\n\nconst client = new EmailImapClient(config);\nawait client.connect();\n\n// Fetch the last 10 emails\nconst emails = await client.fetchLatest(10);\nconsole.log(emails);\n```\n\n### 2. Parse Emails\n\n```javascript\nimport { toFetchedEmail } from 'email-agent-core';\n\n// Transform raw IMAP message to clean email object\nconst parsedEmail = toFetchedEmail(rawMessage);\n\nconsole.log({\n  uid: parsedEmail.uid,\n  from: parsedEmail.from,\n  subject: parsedEmail.subject,\n  text: parsedEmail.text,\n  date: parsedEmail.date\n});\n```\n\n### 3. Classify Emails with AI\n\n#### Using Local LLM (LlamaCppLLM)\n\n```javascript\nimport { EmailClassifier, LlamaCppLLM } from 'email-agent-core';\n\n// Initialize local LLM\nconst llm = new LlamaCppLLM({\n  modelPath: './models/llama-model.gguf',\n  temperature: 0.7\n});\n\n// Create classifier\nconst classifier = new EmailClassifier(llm);\n\n// Classify an email\nconst classification = await classifier.execute({\n  subject: 'Booking Request for December',\n  body: 'Hi, I would like to book a room for 2 nights...'\n});\n\nconsole.log(classification);\n// {\n//   category: 'booking',\n//   priority: 'high',\n//   sentiment: 'positive',\n//   advert: false,\n//   extractedInfo: {\n//     guestName: 'John Doe',\n//     checkIn: '2024-12-01',\n//     checkOut: '2024-12-03',\n//     numberOfGuests: 2\n//   },\n//   suggestedAction: 'Check availability and respond with pricing',\n//   confidence: 0.95\n// }\n```\n\n#### Using OpenAI\n\n```javascript\nimport { EmailClassifier, OpenAILLM } from 'email-agent-core';\n\n// Initialize OpenAI LLM\nconst llm = new OpenAILLM({\n  model: 'gpt-4o-mini',\n  temperature: 0.2,\n  apiKey: process.env.OPENAI_API_KEY // or your API key\n});\n\n// Create classifier\nconst classifier = new EmailClassifier(llm);\n\n// Classify an email\nconst classification = await classifier.execute({\n  subject: 'Booking Request for December',\n  body: 'Hi, I would like to book a room for 2 nights...'\n});\n\nconsole.log(classification);\n```\n\n### 4. Generate Email Responses\n\n```javascript\nimport { EmailResponseGenerator } from 'email-agent-core';\n\nconst generator = new EmailResponseGenerator(llm);\n\nconst response = await generator.execute({\n  originalEmail: 'Hi, I would like to book a room for 2 nights...',\n  context: {\n    hotelName: 'Grand Hotel',\n    guestName: 'John Doe',\n    requestType: 'booking',\n    roomsAvailable: true,\n    suggestedPrice: 150,\n    checkInDate: '2024-12-01',\n    checkOutDate: '2024-12-03',\n    hotelPolicies: {\n      checkInTime: '3:00 PM',\n      checkOutTime: '11:00 AM',\n      cancellation: 'Free cancellation up to 24 hours before check-in'\n    }\n  }\n});\n\nconsole.log(response);\n// Professional, contextual email response ready to send\n```\n\n## Complete Workflow Example\n\nHere's a complete example that fetches emails, classifies them, and generates responses:\n\n```javascript\nimport { \n  fetchLatestEmails,\n  EmailClassifier,\n  EmailResponseGenerator,\n  LlamaCppLLM \n} from 'email-agent-core';\n\nasync function processEmails() {\n  // Initialize LLM\n  const llm = new LlamaCppLLM({\n    modelPath: './models/llama-model.gguf',\n    temperature: 0.7\n  });\n\n  // Create agents\n  const classifier = new EmailClassifier(llm);\n  const responseGenerator = new EmailResponseGenerator(llm);\n\n  // Fetch latest emails\n  const emails = await fetchLatestEmails(5);\n\n  for (const email of emails) {\n    console.log(`Processing: ${email.subject}`);\n\n    // Classify email\n    const classification = await classifier.execute({\n      subject: email.subject,\n      body: email.text\n    });\n\n    console.log('Classification:', classification);\n\n    // Skip if it's an advertisement\n    if (classification.advert) {\n      console.log('Skipping advertisement');\n      continue;\n    }\n\n    // Generate response for important emails\n    if (classification.priority === 'high' || classification.priority === 'urgent') {\n      const response = await responseGenerator.execute({\n        originalEmail: email.text,\n        context: {\n          hotelName: 'Your Hotel Name',\n          guestName: classification.extractedInfo?.guestName,\n          requestType: classification.category,\n          roomsAvailable: true,\n          checkInDate: classification.extractedInfo?.checkIn,\n          checkOutDate: classification.extractedInfo?.checkOut,\n          hotelPolicies: {\n            checkInTime: '3:00 PM',\n            checkOutTime: '11:00 AM',\n            cancellation: 'Free cancellation up to 24 hours before check-in'\n          }\n        }\n      });\n\n      console.log('Generated Response:', response);\n      // Send the response using nodemailer or your email service\n    }\n  }\n}\n\nprocessEmails().catch(console.error);\n```\n\n## Sending Messages\n\nThe package provides a simple `sendEmail()` function to send emails via SMTP. The SMTP configuration is automatically loaded from your `email-agent-core.config.json` file.\n\n### Basic Email Sending\n\n```javascript\nimport { sendEmail } from 'email-agent-core';\n\n// Send a simple text email\nconst result = await sendEmail({\n  to: 'recipient@example.com',\n  subject: 'Hello from email-agent-core',\n  text: 'This is a plain text email message.'\n});\n\nconsole.log('Email sent!', result.messageId);\n```\n\n### Sending HTML Emails\n\n```javascript\nimport { sendEmail } from 'email-agent-core';\n\n// Send an HTML email with both text and HTML versions\nconst result = await sendEmail({\n  to: 'recipient@example.com',\n  subject: 'Welcome to Our Service',\n  text: 'Welcome! This is the plain text version.',\n  html: `\n    \u003chtml\u003e\n      \u003cbody\u003e\n        \u003ch1\u003eWelcome!\u003c/h1\u003e\n        \u003cp\u003eThis is a \u003cstrong\u003eformatted HTML\u003c/strong\u003e email.\u003c/p\u003e\n      \u003c/body\u003e\n    \u003c/html\u003e\n  `\n});\n\nconsole.log('HTML email sent!', result);\n```\n\n### Sending Automated Responses\n\nHere's a complete example that generates and sends an AI-powered response:\n\n```javascript\nimport { \n  fetchLatestEmails,\n  EmailClassifier,\n  EmailResponseGenerator,\n  sendEmail,\n  LlamaCppLLM \n} from 'email-agent-core';\n\nasync function autoRespond() {\n  // Initialize LLM\n  const llm = new LlamaCppLLM({\n    modelPath: './models/llama-model.gguf',\n    temperature: 0.7\n  });\n\n  // Create agents\n  const classifier = new EmailClassifier(llm);\n  const responseGenerator = new EmailResponseGenerator(llm);\n\n  // Fetch latest emails\n  const emails = await fetchLatestEmails(5);\n\n  for (const email of emails) {\n    // Classify email\n    const classification = await classifier.execute({\n      subject: email.subject,\n      body: email.text\n    });\n\n    // Only respond to high priority, non-advertisement emails\n    if (!classification.advert \u0026\u0026 classification.priority === 'high') {\n      // Generate response\n      const response = await responseGenerator.execute({\n        originalEmail: email.text,\n        context: {\n          hotelName: 'Grand Hotel',\n          guestName: classification.extractedInfo?.guestName,\n          requestType: classification.category,\n          roomsAvailable: true,\n          hotelPolicies: {\n            checkInTime: '3:00 PM',\n            checkOutTime: '11:00 AM',\n            cancellation: 'Free cancellation up to 24 hours before check-in'\n          }\n        }\n      });\n\n      // Send the generated response\n      await sendEmail({\n        to: email.from,\n        subject: `Re: ${email.subject}`,\n        text: response,\n        html: `\u003cp\u003e${response.replace(/\\n/g, '\u003cbr\u003e')}\u003c/p\u003e`\n      });\n\n      console.log(`✅ Sent response to ${email.from}`);\n    }\n  }\n}\n\nautoRespond().catch(console.error);\n```\n\n### SendEmail Options\n\nThe `sendEmail()` function accepts the following options:\n\n```typescript\ninterface SendEmailOptions {\n  to: string;         // Required: Recipient email address\n  subject?: string;   // Email subject line\n  text?: string;      // Plain text version of the email\n  html?: string;      // HTML version of the email\n  user?: string;      // Optional: Override sender (defaults to config)\n}\n```\n\n### SendEmail Result\n\nThe function returns a promise that resolves to:\n\n```typescript\ninterface SendEmailResult {\n  messageId: string;           // Unique message identifier\n  accepted: string[];          // Array of accepted recipient addresses\n  rejected: string[];          // Array of rejected recipient addresses\n}\n```\n\n### Important Notes\n\n- **Configuration Required**: Ensure your `email-agent-core.config.json` includes valid SMTP settings\n- **Authentication**: For Gmail, you'll need an app-specific password (see Configuration section)\n- **Error Handling**: Always wrap `sendEmail()` in try-catch blocks to handle connection errors\n- **Rate Limiting**: Be mindful of your email provider's sending limits\n- **Email Format**: Providing both `text` and `html` ensures compatibility with all email clients\n\n## API Reference\n\n### EmailImapClient\n\nConnect to IMAP servers and fetch emails.\n\n**Constructor:**\n```javascript\nnew EmailImapClient(config: ImapConfig)\n```\n\n**Config:**\n```typescript\ninterface ImapConfig {\n  host: string;      // IMAP server host\n  port: number;      // IMAP server port (usually 993 for SSL)\n  tls: boolean;      // Use TLS/SSL\n  user: string;      // Email address\n  pass: string;      // Password or app-specific password\n}\n```\n\n**Methods:**\n- `async connect()`: Connect to the IMAP server\n- `async fetchLatest(limit?: number)`: Fetch the latest N emails (default: 10)\n- `async disconnect()`: Close the IMAP connection\n\n### fetchLatestEmails(limit)\n\nHigh-level function that loads config from environment, connects, and fetches emails.\n\n```javascript\nconst emails = await fetchLatestEmails(10);\n```\n\nReturns an array of parsed email objects.\n\n### toFetchedEmail(message)\n\nTransform raw IMAP message to clean email object.\n\n**Returns:**\n```typescript\n{\n  uid: number;\n  date: Date | null;\n  from: string | null;\n  to: string | null;\n  subject: string;\n  text: string;\n  html: string;\n  messageId: string;\n  flags: string[];\n}\n```\n\n### EmailClassifier\n\nAI-powered email classification agent.\n\n**Constructor:**\n```javascript\nconst classifier = new EmailClassifier(\n  llm: LlamaCppLLM,\n  promptTemplate?: TemplatePrompt  // Optional: custom prompt template\n)\n```\n\n**Methods:**\n```javascript\nasync execute(input: { subject: string; body: string }): Promise\u003cEmailClassification\u003e\n```\n\n**Classification Result:**\n```typescript\ninterface EmailClassification {\n  category: 'booking' | 'inquiry' | 'complaint' | 'cancellation' | 'other';\n  priority: 'urgent' | 'high' | 'medium' | 'low';\n  sentiment: 'positive' | 'neutral' | 'negative';\n  advert: boolean;\n  extractedInfo: {\n    guestName?: string;\n    checkIn?: string;\n    checkOut?: string;\n    roomType?: string;\n    numberOfGuests?: number;\n  };\n  suggestedAction: string;\n  confidence: number; // 0.0 - 1.0\n}\n```\n\n**Customizing the Classification Prompt:**\n\nThe `EmailClassifier` uses a default prompt template that you can access and customize:\n\n```javascript\nimport { \n  EmailClassifier, \n  DEFAULT_CLASSIFICATION_TEMPLATE,\n  TemplatePrompt,\n  LlamaCppLLM \n} from 'email-agent-core';\n\n// Access the default template\nconsole.log(DEFAULT_CLASSIFICATION_TEMPLATE);\n\n// Option 1: Use the default template\nconst classifier = new EmailClassifier(llm);\n\n// Option 2: Customize the template\nconst customTemplate = `\nAnalyze this email and provide JSON classification.\n\nEmail Subject: {subject}\nEmail Body: {body}\n\nReturn JSON with: category, priority, sentiment, advert, extractedInfo, suggestedAction, confidence\n`;\n\nconst customClassifier = new EmailClassifier(\n  llm,\n  TemplatePrompt.fromTemplate(customTemplate)\n);\n```\n\n### EmailResponseGenerator\n\nGenerate professional email responses with context.\n\n**Constructor:**\n```javascript\nconst generator = new EmailResponseGenerator(\n  llm: LlamaCppLLM,\n  promptTemplate?: TemplatePrompt  // Optional: custom prompt template\n)\n```\n\n**Methods:**\n```javascript\nasync execute(input: {\n  originalEmail: string;\n  context: ResponseContext;\n}): Promise\u003cstring\u003e\n```\n\n**Response Context:**\n```typescript\ninterface ResponseContext {\n  hotelName: string;\n  guestName?: string;\n  requestType: string;\n  roomsAvailable: boolean;\n  suggestedPrice?: number;\n  checkInDate?: string;\n  checkOutDate?: string;\n  hotelPolicies: {\n    checkInTime: string;\n    checkOutTime: string;\n    cancellation: string;\n  };\n}\n```\n\n**Customizing the Response Prompt:**\n\nThe `EmailResponseGenerator` uses a default prompt template that you can access and customize:\n\n```javascript\nimport { \n  EmailResponseGenerator, \n  DEFAULT_RESPONSE_TEMPLATE,\n  TemplatePrompt,\n  LlamaCppLLM \n} from 'email-agent-core';\n\n// Access the default template\nconsole.log(DEFAULT_RESPONSE_TEMPLATE);\n\n// Option 1: Use the default template\nconst generator = new EmailResponseGenerator(llm);\n\n// Option 2: Customize the template\nconst customTemplate = `\nYou are responding to an email for {hotelName}.\n\nGuest: {guestName}\nRequest: {requestType}\nOriginal Email: {originalEmail}\n\nWrite a professional, friendly response.\n`;\n\nconst customGenerator = new EmailResponseGenerator(\n  llm,\n  TemplatePrompt.fromTemplate(customTemplate)\n);\n\n// Use the custom generator\nconst response = await customGenerator.execute({\n  originalEmail: email.text,\n  context: {\n    hotelName: 'Grand Hotel',\n    guestName: 'John Doe',\n    requestType: 'booking',\n    roomsAvailable: true,\n    hotelPolicies: {\n      checkInTime: '3:00 PM',\n      checkOutTime: '11:00 AM',\n      cancellation: 'Free cancellation up to 24 hours before check-in'\n    }\n  }\n});\n```\n\n**Available Template Variables:**\n\nThe default response template supports these variables:\n- `{hotelName}` - Name of the hotel\n- `{guestName}` - Name of the guest\n- `{requestType}` - Type of request (booking, inquiry, etc.)\n- `{originalEmail}` - The original email content\n- `{employeeLine}` - Optional employee name line\n- `{roomsAvailable}` - Yes/No for room availability\n- `{suggestedPriceLine}` - Optional price suggestion\n- `{checkInLine}` - Optional check-in date\n- `{checkOutLine}` - Optional check-out date\n- `{policyBlock}` - Hotel policies block\n\n### LlamaCppLLM\n\nLocal LLM interface using node-llama-cpp.\n\n**Constructor:**\n```javascript\nconst llm = new LlamaCppLLM(options: LlamaCppLLMOptions)\n```\n\n**Options:**\n```typescript\ninterface LlamaCppLLMOptions {\n  modelPath: string;       // Path to .gguf model file\n  temperature?: number;    // Sampling temperature (0.0 - 1.0)\n  maxTokens?: number;      // Maximum tokens to generate\n  topP?: number;           // Nucleus sampling\n  topK?: number;           // Top-K sampling\n  // ... additional llama.cpp options\n}\n```\n\n**Methods:**\n- `async run(messages: BaseMessage[]): Promise\u003cAIMessage\u003e`: Generate completion from messages\n\n### OpenAILLM\n\nCloud-based LLM interface using OpenAI API.\n\n**Constructor:**\n```javascript\nconst llm = new OpenAILLM(options: OpenAILLMOptions)\n```\n\n**Options:**\n```typescript\ninterface OpenAILLMOptions {\n  model: string;           // OpenAI model name (e.g., 'gpt-4o-mini', 'gpt-4', 'gpt-3.5-turbo')\n  apiKey: string;          // Your OpenAI API key\n  temperature?: number;    // Sampling temperature (0.0 - 2.0)\n  maxTokens?: number;      // Maximum tokens to generate\n  topP?: number;           // Nucleus sampling\n  // ... additional OpenAI options\n}\n```\n\n**Methods:**\n- `async run(messages: BaseMessage[]): Promise\u003cAIMessage\u003e`: Generate completion from messages\n\n**Example:**\n```javascript\nimport { OpenAILLM } from 'email-agent-core';\n\nconst llm = new OpenAILLM({\n  model: 'gpt-4o-mini',\n  temperature: 0.2,\n  apiKey: process.env.OPENAI_API_KEY\n});\n```\n\n### Action Base Class\n\nAll agents extend the `Action` class, providing composability.\n\n**Methods:**\n- `async run(input: any, config?: any)`: Execute the action\n- `async* streamOutput(input: any, config?: any)`: Stream output chunks\n- `async runBatch(inputs: any[], config?: any)`: Process multiple inputs\n- `chain(other: Action)`: Chain this action with another\n\n**Example - Chaining Actions:**\n```javascript\n// Create a pipeline that classifies then generates response\nconst pipeline = classifier.chain(responseGenerator);\nconst result = await pipeline.run(input);\n```\n\n### sendEmail(options)\n\nSend emails via SMTP using the configuration from `email-agent-core.config.json`.\n\n**Parameters:**\n```typescript\ninterface SendEmailOptions {\n  to: string;         // Required: Recipient email address\n  subject?: string;   // Email subject line\n  text?: string;      // Plain text version of the email\n  html?: string;      // HTML version of the email\n  user?: string;      // Optional: Override sender (defaults to config)\n}\n```\n\n**Returns:**\n```typescript\nPromise\u003cSendEmailResult\u003e\n\ninterface SendEmailResult {\n  messageId: string;           // Unique message identifier\n  accepted: string[];          // Array of accepted recipient addresses\n  rejected: string[];          // Array of rejected recipient addresses\n}\n```\n\n**Example:**\n```javascript\nimport { sendEmail } from 'email-agent-core';\n\nconst result = await sendEmail({\n  to: 'recipient@example.com',\n  subject: 'Hello',\n  text: 'Plain text message',\n  html: '\u003cp\u003eHTML message\u003c/p\u003e'\n});\n\nconsole.log('Sent:', result.messageId);\n```\n\n### loadEmailConfig()\n\nLoad email configuration from `email-agent-core.config.json` in the project root.\n\n**Returns:**\n```typescript\ninterface EmailConfig {\n  imap: {\n    host: string;\n    port: number;\n    tls: boolean;\n    user: string;\n    pass: string;\n  };\n  smtp: {\n    host: string;\n    port: number;\n    secure: boolean;\n    user: string;\n    pass: string;\n  };\n}\n```\n\n**Example:**\n```javascript\nimport { loadEmailConfig } from 'email-agent-core';\n\nconst config = loadEmailConfig();\nconsole.log('IMAP host:', config.imap.host);\n```\n\n**Throws:** Error if `email-agent-core.config.json` is not found.\n\n### Message Classes\n\nMessage classes for LLM communication.\n\n#### BaseMessage\n\nBase class for all message types.\n\n**Properties:**\n- `content: string` - Message content\n- `role: string` - Message role (system, user, assistant, tool)\n\n#### SystemMessage\n\nSystem-level instructions for the LLM.\n\n```javascript\nimport { SystemMessage } from 'email-agent-core';\n\nconst msg = new SystemMessage('You are a helpful assistant.');\n```\n\n#### HumanMessage\n\nUser input messages.\n\n```javascript\nimport { HumanMessage } from 'email-agent-core';\n\nconst msg = new HumanMessage('What is the weather today?');\n```\n\n#### AIMessage\n\nAssistant/AI response messages.\n\n```javascript\nimport { AIMessage } from 'email-agent-core';\n\nconst msg = new AIMessage('The weather is sunny today.');\n```\n\n#### ToolMessage\n\nTool execution result messages.\n\n```javascript\nimport { ToolMessage } from 'email-agent-core';\n\nconst msg = new ToolMessage('Tool result data', 'tool-call-id');\n```\n\n### TemplatePrompt\n\nTemplate-based prompt with variable substitution.\n\n**Static Methods:**\n- `static fromTemplate(template: string): TemplatePrompt` - Create from template string\n\n**Methods:**\n- `format(variables: Record\u003cstring, any\u003e): string` - Format template with variables\n\n**Example:**\n```javascript\nimport { TemplatePrompt } from 'email-agent-core';\n\nconst template = TemplatePrompt.fromTemplate(`\nHello {name},\n\nYour order #{orderId} has been {status}.\n`);\n\nconst formatted = template.format({\n  name: 'John',\n  orderId: '12345',\n  status: 'shipped'\n});\n```\n\n**Template Variables:**\nUse `{variableName}` syntax for variable placeholders.\n\n### Output Parsers\n\nParse and validate LLM output.\n\n#### JsonOutputParser\n\nParse JSON output from LLM responses.\n\n```javascript\nimport { JsonOutputParser } from 'email-agent-core';\n\nconst parser = new JsonOutputParser();\nconst result = await parser.parse('{\"key\": \"value\"}');\n// Returns: { key: \"value\" }\n```\n\n**Methods:**\n- `async parse(text: string): Promise\u003cany\u003e` - Parse JSON string to object\n- `getFormatInstructions(): string` - Get instructions for LLM\n\n**Throws:** `OutputParserException` if JSON is invalid.\n\n#### StringOutputParser\n\nParse plain text output from LLM responses.\n\n```javascript\nimport { StringOutputParser } from 'email-agent-core';\n\nconst parser = new StringOutputParser();\nconst result = await parser.parse('Hello world');\n// Returns: \"Hello world\"\n```\n\n**Methods:**\n- `async parse(text: string): Promise\u003cstring\u003e` - Parse text (returns as-is)\n\n### BasePrompt\n\nBase class for creating custom prompts.\n\n**Methods:**\n- `abstract format(variables: any): string` - Format prompt with variables\n\n**Example - Custom Prompt:**\n```javascript\nimport { BasePrompt } from 'email-agent-core';\n\nclass CustomPrompt extends BasePrompt {\n  format(variables) {\n    return `Custom prompt with ${variables.value}`;\n  }\n}\n```\n\n### BaseParser\n\nBase class for creating custom output parsers.\n\n**Methods:**\n- `abstract parse(text: string): Promise\u003cT\u003e` - Parse LLM output\n- `getFormatInstructions(): string` - Get format instructions (optional)\n\n**Example - Custom Parser:**\n```javascript\nimport { BaseParser } from 'email-agent-core';\n\nclass CustomParser extends BaseParser {\n  async parse(text) {\n    // Custom parsing logic\n    return text.trim().toUpperCase();\n  }\n}\n```\n\n## Configuration\n\n### Project Initialization\n\nInitialize your project with:\n\n```bash\nnpx email-agent-core init\n```\n\nThis command creates a configuration file:\n\n```\nemail-agent-core.config.json\n```\n\n### email-agent-core.config.json\n\nAll email settings are now stored in this JSON file instead of environment variables.\n\n```\n{\n  \"imap\": {\n    \"host\": \"imap.gmail.com\",\n    \"port\": 993,\n    \"tls\": true,\n    \"user\": \"your-email@gmail.com\",\n    \"password\": \"your-password\"\n  },\n  \"smtp\": {\n    \"host\": \"smtp.gmail.com\",\n    \"port\": 587,\n    \"secure\": true,\n    \"user\": \"your-email@gmail.com\",\n    \"password\": \"your-password\"\n  }\n}\n```\n\n### Loading Configuration\n\nLoad the configuration within your project:\n\n```\nimport { loadEmailConfig } from \"email-agent-core\";\n\nconst config = loadEmailConfig();\n```\n\n## Use Cases\n\n### 1. Customer Support Automation\n- Automatically classify support tickets\n- Generate draft responses for common inquiries\n- Prioritize urgent issues\n- Extract key information (customer name, issue details, etc.)\n\n### 2. Hotel/Booking Management\n- Process booking requests automatically\n- Extract reservation details (dates, guests, room preferences)\n- Generate professional responses with availability and pricing\n- Handle cancellations and modifications\n\n### 3. Email Triage\n- Filter out spam and advertisements\n- Categorize emails by department or topic\n- Route to appropriate handlers based on priority and sentiment\n- Extract action items and deadlines\n\n### 4. Sales Lead Management\n- Identify potential sales inquiries\n- Extract contact information and requirements\n- Generate personalized follow-up emails\n- Score leads by priority and interest level\n\n### 5. Newsletter/Marketing Automation\n- Classify feedback and responses\n- Analyze sentiment of customer reactions\n- Generate personalized responses to inquiries\n- Extract unsubscribe requests\n\n## Privacy \u0026 Security\n\nThe package supports two LLM options with different privacy implications:\n\n### Local LLM (LlamaCppLLM) - Maximum Privacy\n- **Local Processing**: All AI processing happens locally using `node-llama-cpp`\n- **No External API Calls**: Email content never leaves your server\n- **GDPR Compliant**: Full control over data processing and storage\n- **Offline Capable**: Works without internet connection for AI processing\n\n### Cloud LLM (OpenAI) - Convenience \u0026 Performance\n- **External API**: Email content is sent to OpenAI for processing\n- **API Key Required**: Secure API key authentication\n- **Privacy Considerations**: Review OpenAI's data usage policies\n- **High Performance**: Fast inference with powerful models\n\n### General Security\n- **Secure Connections**: TLS/SSL support for IMAP/SMTP connections\n- **Configuration Security**: Store credentials securely (use environment variables)\n- **Flexible Choice**: Choose the LLM provider that fits your privacy requirements\n\n## Testing\n\n```bash\nnpm test\n```\n\nSee `test-real.js` for comprehensive workflow examples and tests including:\n- Real IMAP/SMTP integration tests\n- AI email classification with both local and OpenAI models\n- Complete workflow demonstrations\n- Email sending examples\n\n## License\n\nMIT\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## Additional Resources\n\n- [node-llama-cpp Documentation](https://github.com/withcatai/node-llama-cpp)\n- [IMAP Protocol RFC](https://tools.ietf.org/html/rfc3501)\n- [Email Parsing with mailparser](https://nodemailer.com/extras/mailparser/)\n\n## Important Notes\n\n### LLM Model Requirements \n\nYou need to download a compatible GGUF model file if you want to use local inference. Popular options:\n- Llama 2 or 3 models\n- Mistral models\n- Phi models\n\nDownload from [Hugging Face](https://huggingface.co/models?library=gguf) and place in your project directory.\n\n### Gmail App Passwords\n\nIf using Gmail, you'll need to:\n1. Enable 2-factor authentication\n2. Generate an app-specific password\n3. Use the app password instead of your regular password\n\n### Rate Limiting\n\nBe mindful of:\n- IMAP server rate limits\n- LLM inference time (local models can be slow)\n- Memory usage with large models\n\n## Future Enhancements\n\nPlanned features:\n- Support for more LLM providers (Anthropic, Google AI, etc.)\n- More Agent features like tool use etc\n- Scheduled email processing with cron\n- Advanced email threading and conversation tracking\n\n## Tips\n\n1. **Choose Your LLM Provider**: \n   - Use **OpenAI** for quick setup, high performance, and minimal resource requirements\n   - Use **Local LLM** for maximum privacy, offline capability, and no API costs\n2. **Start Small**: Begin with a small model (7B parameters) for faster local inference\n3. **API Keys**: Store OpenAI API keys in environment variables, never in code\n4. **Batch Processing**: Use `runBatch()` for processing multiple emails efficiently\n5. **Streaming**: Use `streamOutput()` for real-time response generation\n6. **Chaining**: Combine agents using `chain()` for complex workflows\n7. **Error Handling**: Always wrap agent calls in try-catch blocks\n8. **Testing**: Test thoroughly with sample emails before production use (see `test-real.js`)\n\n## Support\n\nFor issues, questions, or contributions, please open an issue on GitHub.\n\n---\n\nBuilt with ❤️ for developers who need intelligent email automation.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpguso%2Femail-agent-core","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpguso%2Femail-agent-core","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpguso%2Femail-agent-core/lists"}