matimo-examples 0.1.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +49 -0
- package/LICENSE +21 -0
- package/README.md +525 -0
- package/agents/decorator-pattern-agent.ts +368 -0
- package/agents/factory-pattern-agent.ts +253 -0
- package/agents/langchain-agent.ts +146 -0
- package/edit/edit-decorator.ts +178 -0
- package/edit/edit-factory.ts +138 -0
- package/edit/edit-langchain.ts +292 -0
- package/execute/execute-decorator.ts +49 -0
- package/execute/execute-factory.ts +46 -0
- package/execute/execute-langchain.ts +232 -0
- package/github/github-decorator.ts +326 -0
- package/github/github-factory.ts +355 -0
- package/github/github-langchain.ts +206 -0
- package/github/github-with-approval.ts +228 -0
- package/gmail/README.md +345 -0
- package/gmail/gmail-decorator.ts +216 -0
- package/gmail/gmail-factory.ts +231 -0
- package/gmail/gmail-langchain.ts +201 -0
- package/hubspot/README.md +316 -0
- package/hubspot/hubspot-decorator.ts +180 -0
- package/hubspot/hubspot-factory.ts +188 -0
- package/hubspot/hubspot-langchain.ts +222 -0
- package/logger-example.ts +40 -0
- package/mailchimp/README.md +321 -0
- package/mailchimp/mailchimp-decorator.ts +277 -0
- package/mailchimp/mailchimp-factory.ts +187 -0
- package/mailchimp/mailchimp-langchain.ts +155 -0
- package/notion/README.md +293 -0
- package/notion/notion-decorator.ts +275 -0
- package/notion/notion-factory.ts +256 -0
- package/notion/notion-langchain.ts +237 -0
- package/package.json +79 -0
- package/postgres/README.md +188 -0
- package/postgres/postgres-decorator.ts +198 -0
- package/postgres/postgres-factory.ts +180 -0
- package/postgres/postgres-langchain.ts +213 -0
- package/postgres/postgres-with-approval.ts +344 -0
- package/read/read-decorator.ts +154 -0
- package/read/read-factory.ts +121 -0
- package/read/read-langchain.ts +273 -0
- package/search/search-decorator.ts +206 -0
- package/search/search-factory.ts +146 -0
- package/search/search-langchain.ts +255 -0
- package/slack/README.md +339 -0
- package/slack/slack-decorator.ts +245 -0
- package/slack/slack-factory.ts +226 -0
- package/slack/slack-langchain.ts +242 -0
- package/tsconfig.json +20 -0
- package/twilio/README.md +309 -0
- package/twilio/twilio-decorator.ts +288 -0
- package/twilio/twilio-factory.ts +238 -0
- package/twilio/twilio-langchain.ts +218 -0
- package/web/web-decorator.ts +52 -0
- package/web/web-factory.ts +70 -0
- package/web/web-langchain.ts +163 -0
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* ============================================================================
|
|
4
|
+
* HUBSPOT TOOLS - LANGCHAIN AI AGENT EXAMPLE
|
|
5
|
+
* ============================================================================
|
|
6
|
+
*
|
|
7
|
+
* PATTERN: True AI Agent with OpenAI + LangChain
|
|
8
|
+
* ─────────────────────────────────────────────────────────────────────────
|
|
9
|
+
* This is a REAL AI agent that:
|
|
10
|
+
* 1. Takes natural language user requests
|
|
11
|
+
* 2. Uses OpenAI LLM (GPT-4o-mini) to decide which HubSpot tools to use
|
|
12
|
+
* 3. Generates appropriate parameters based on context
|
|
13
|
+
* 4. Executes tools autonomously
|
|
14
|
+
* 5. Processes results and responds naturally
|
|
15
|
+
*
|
|
16
|
+
* Use this pattern when:
|
|
17
|
+
* ✅ Building true autonomous AI agents
|
|
18
|
+
* ✅ LLM should decide which tools to use
|
|
19
|
+
* ✅ Complex workflows with LLM reasoning
|
|
20
|
+
* ✅ Multi-step agentic processes
|
|
21
|
+
* ✅ User gives high-level instructions (not low-level API calls)
|
|
22
|
+
*
|
|
23
|
+
* SETUP:
|
|
24
|
+
* ─────────────────────────────────────────────────────────────────────────
|
|
25
|
+
* 1. Create .env file:
|
|
26
|
+
* MATIMO_HUBSPOT_API_KEY=pat-na1-xxxxxxxxxxxxx
|
|
27
|
+
* OPENAI_API_KEY=sk-xxxxxxxxxxxxx
|
|
28
|
+
*
|
|
29
|
+
* 2. Install dependencies:
|
|
30
|
+
* npm install
|
|
31
|
+
*
|
|
32
|
+
* USAGE:
|
|
33
|
+
* ─────────────────────────────────────────────────────────────────────────
|
|
34
|
+
* export MATIMO_HUBSPOT_API_KEY=pat-na1-xxxx
|
|
35
|
+
* export OPENAI_API_KEY=sk-xxxx
|
|
36
|
+
* npm run hubspot:langchain
|
|
37
|
+
*
|
|
38
|
+
* WHAT IT DOES:
|
|
39
|
+
* ─────────────────────────────────────────────────────────────────────────
|
|
40
|
+
* This example shows an AI agent that can:
|
|
41
|
+
* 1. Create contacts in HubSpot
|
|
42
|
+
* 2. Create companies
|
|
43
|
+
* 3. List existing contacts
|
|
44
|
+
* 4. Create products
|
|
45
|
+
* 5. Create invoices
|
|
46
|
+
* 6. Respond naturally in conversation style
|
|
47
|
+
*
|
|
48
|
+
* Example conversation:
|
|
49
|
+
* User: "Create a new contact with email test@example.com"
|
|
50
|
+
* AI Agent: "I'll create a new contact with that email..."
|
|
51
|
+
* [AI Agent calls hubspot-create-contact tool]
|
|
52
|
+
* AI Agent: "Done! Contact created with ID xxxxxx."
|
|
53
|
+
*
|
|
54
|
+
* ============================================================================
|
|
55
|
+
*/
|
|
56
|
+
|
|
57
|
+
import 'dotenv/config';
|
|
58
|
+
import path from 'path';
|
|
59
|
+
import { fileURLToPath } from 'url';
|
|
60
|
+
import { createAgent } from 'langchain';
|
|
61
|
+
import { ChatOpenAI } from '@langchain/openai';
|
|
62
|
+
import { MatimoInstance, convertToolsToLangChain, ToolDefinition } from '@matimo/core';
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Run AI Agent with HubSpot tools
|
|
66
|
+
* The agent receives natural language requests and decides which HubSpot tools to use
|
|
67
|
+
*/
|
|
68
|
+
async function runHubSpotAIAgent() {
|
|
69
|
+
console.info('\n╔════════════════════════════════════════════════════════╗');
|
|
70
|
+
console.info('║ HubSpot AI Agent - LangChain + OpenAI ║');
|
|
71
|
+
console.info('║ True autonomous agent with LLM reasoning ║');
|
|
72
|
+
console.info('╚════════════════════════════════════════════════════════╝\n');
|
|
73
|
+
|
|
74
|
+
// Check required environment variables
|
|
75
|
+
const hubspotKey = process.env.MATIMO_HUBSPOT_API_KEY;
|
|
76
|
+
if (!hubspotKey) {
|
|
77
|
+
console.error('❌ Error: MATIMO_HUBSPOT_API_KEY not set in .env');
|
|
78
|
+
console.info(' Go to: https://app.hubapi.com/settings/integrations/service-keys');
|
|
79
|
+
console.info(' Create a service key and copy it');
|
|
80
|
+
process.exit(1);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const openaiKey = process.env.OPENAI_API_KEY;
|
|
84
|
+
if (!openaiKey) {
|
|
85
|
+
console.error('❌ Error: OPENAI_API_KEY not set in .env');
|
|
86
|
+
console.info(' Set it: export OPENAI_API_KEY="sk-..."');
|
|
87
|
+
console.info(' Get one from: https://platform.openai.com/account/api-keys');
|
|
88
|
+
process.exit(1);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
console.info(`🔑 HubSpot Service Key is set`);
|
|
92
|
+
console.info(`🔑 OpenAI API Key is set`);
|
|
93
|
+
console.info(`🤖 Using OpenAI (GPT-4o-mini) as the AI agent\n`);
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
// Initialize Matimo with auto-discovery
|
|
97
|
+
console.info('🚀 Initializing Matimo...');
|
|
98
|
+
const matimo = await MatimoInstance.init({ autoDiscover: true });
|
|
99
|
+
|
|
100
|
+
// Get HubSpot tools and convert to LangChain format
|
|
101
|
+
console.info('💼 Loading HubSpot tools...');
|
|
102
|
+
const matimoTools = matimo.listTools();
|
|
103
|
+
const hubspotTools = matimoTools.filter((t) => t.name.startsWith('hubspot-'));
|
|
104
|
+
console.info(`✅ Loaded ${hubspotTools.length} HubSpot tools\n`);
|
|
105
|
+
|
|
106
|
+
// Select key HubSpot tools for the agent
|
|
107
|
+
const keyHubSpotTools = hubspotTools.filter((t) =>
|
|
108
|
+
[
|
|
109
|
+
'hubspot-create-contact',
|
|
110
|
+
'hubspot-get-contact',
|
|
111
|
+
'hubspot-list-contacts',
|
|
112
|
+
'hubspot-create-company',
|
|
113
|
+
'hubspot-create-product',
|
|
114
|
+
'hubspot-create-invoice',
|
|
115
|
+
].includes(t.name)
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
// ✅ Convert Matimo tools to LangChain format
|
|
119
|
+
console.info('🔧 Converting tools to LangChain format...');
|
|
120
|
+
const langchainTools = await convertToolsToLangChain(
|
|
121
|
+
keyHubSpotTools as ToolDefinition[],
|
|
122
|
+
matimo,
|
|
123
|
+
{
|
|
124
|
+
MATIMO_HUBSPOT_API_KEY: hubspotKey,
|
|
125
|
+
}
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
console.info(`✅ Converted ${langchainTools.length} tools\n`);
|
|
129
|
+
|
|
130
|
+
// Initialize OpenAI LLM
|
|
131
|
+
console.info('🤖 Initializing OpenAI (GPT-4o-mini) LLM...');
|
|
132
|
+
const model = new ChatOpenAI({
|
|
133
|
+
modelName: 'gpt-4o-mini',
|
|
134
|
+
temperature: 0.7,
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// Create agent
|
|
138
|
+
console.info('🔧 Creating agent...\n');
|
|
139
|
+
const agent = await createAgent({
|
|
140
|
+
model,
|
|
141
|
+
tools: langchainTools as any[], // Type casting for LangChain tools
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
// Define agent tasks (natural language requests)
|
|
145
|
+
const userRequests = [
|
|
146
|
+
{
|
|
147
|
+
title: 'Example 1: Create a new contact',
|
|
148
|
+
request:
|
|
149
|
+
'Create a new contact for a prospect named John Smith with email john.smith@company.com',
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
title: 'Example 2: Create a company',
|
|
153
|
+
request: 'Add a new company called TechCorp for tracking in HubSpot',
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
title: 'Example 3: Create a product',
|
|
157
|
+
request:
|
|
158
|
+
'Create a new product called "Premium Analytics Suite" priced at $299.99 with description "Advanced analytics for enterprise use"',
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
title: 'Example 4: List contacts',
|
|
162
|
+
request: 'How many contacts do we have in HubSpot? Show me the first 5 with their emails.',
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
title: 'Example 5: Create an invoice',
|
|
166
|
+
request: 'Generate a new invoice in USD for billing',
|
|
167
|
+
},
|
|
168
|
+
];
|
|
169
|
+
|
|
170
|
+
console.info('🧪 Running AI Agent Tasks');
|
|
171
|
+
console.info('═'.repeat(60));
|
|
172
|
+
|
|
173
|
+
// Run each task through the agent
|
|
174
|
+
for (const task of userRequests) {
|
|
175
|
+
console.info(`\n${task.title}`);
|
|
176
|
+
console.info('─'.repeat(60));
|
|
177
|
+
console.info(`👤 User: "${task.request}"\n`);
|
|
178
|
+
|
|
179
|
+
try {
|
|
180
|
+
const response = await agent.invoke({
|
|
181
|
+
messages: [
|
|
182
|
+
{
|
|
183
|
+
role: 'user',
|
|
184
|
+
content: task.request,
|
|
185
|
+
},
|
|
186
|
+
],
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
// Get the last message from the agent
|
|
190
|
+
const lastMessage = response.messages[response.messages.length - 1];
|
|
191
|
+
if (lastMessage) {
|
|
192
|
+
if (typeof lastMessage.content === 'string') {
|
|
193
|
+
console.info(`🤖 Agent: ${lastMessage.content}\n`);
|
|
194
|
+
} else {
|
|
195
|
+
console.info(`🤖 Agent:`, lastMessage.content, '\n');
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
} catch (error) {
|
|
199
|
+
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
200
|
+
console.info(`⚠️ Agent error: ${errorMsg}\n`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
console.info('═'.repeat(60));
|
|
205
|
+
console.info('✨ AI Agent Examples Complete!\n');
|
|
206
|
+
console.info('Key Features:');
|
|
207
|
+
console.info(' ✅ Real LLM (OpenAI) decides which tools to use');
|
|
208
|
+
console.info(' ✅ Natural language requests, not API calls');
|
|
209
|
+
console.info(' ✅ LLM generates tool parameters based on context');
|
|
210
|
+
console.info(' ✅ Agentic reasoning and decision-making');
|
|
211
|
+
console.info(' ✅ Multi-step workflows with tool chaining\n');
|
|
212
|
+
} catch (error) {
|
|
213
|
+
console.error('❌ Error:', error instanceof Error ? error.message : String(error));
|
|
214
|
+
if (error instanceof Error && error.stack) {
|
|
215
|
+
console.error('Stack:', error.stack);
|
|
216
|
+
}
|
|
217
|
+
process.exit(1);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Run the AI agent
|
|
222
|
+
runHubSpotAIAgent().catch(console.error);
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Example: Using Matimo with Winston Logger for Production
|
|
3
|
+
* Demonstrates logging with different log levels and formats
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { MatimoInstance } from '@matimo/core';
|
|
7
|
+
|
|
8
|
+
async function main() {
|
|
9
|
+
// Initialize Matimo with debug logging
|
|
10
|
+
const matimo = await MatimoInstance.init({
|
|
11
|
+
toolPaths: ['./packages/slack/tools'],
|
|
12
|
+
logLevel: 'debug',
|
|
13
|
+
logFormat: 'json', // Use JSON for production
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
// Get the logger instance
|
|
17
|
+
const logger = matimo.getLogger();
|
|
18
|
+
|
|
19
|
+
// Log examples
|
|
20
|
+
logger.info('User action initiated', {
|
|
21
|
+
userId: 'user_123',
|
|
22
|
+
action: 'list_tools',
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
logger.debug('Debug info for development', {
|
|
26
|
+
toolCount: matimo.listTools().length,
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
logger.warn('Missing optional parameter', {
|
|
30
|
+
param: 'message_blocks',
|
|
31
|
+
using_fallback: true,
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// List tools
|
|
35
|
+
const tools = matimo.listTools();
|
|
36
|
+
logger.info(`Found ${tools.length} tools`, { tools: tools.map((t) => t.name) });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Run the example
|
|
40
|
+
main().catch(console.error);
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
# Mailchimp Tools Examples
|
|
2
|
+
|
|
3
|
+
Example directory contains **3 example patterns** showing different ways to use Matimo's Mailchimp tools:
|
|
4
|
+
1. **Factory Pattern** - Direct SDK execution (simplest)
|
|
5
|
+
2. **Decorator Pattern** - Class-based with @tool decorators
|
|
6
|
+
3. **LangChain Pattern** - AI-driven with OpenAI agent
|
|
7
|
+
|
|
8
|
+
All examples are **fully working** and demonstrate real Mailchimp operations (audiences, subscribers, and campaigns).
|
|
9
|
+
|
|
10
|
+
## 🚀 Quick Start
|
|
11
|
+
|
|
12
|
+
### 1. Create a Mailchimp API Key
|
|
13
|
+
|
|
14
|
+
1. Log in to your [Mailchimp account](https://login.mailchimp.com/)
|
|
15
|
+
2. Navigate to **Account & Billing** → **Extras** → **API Keys**
|
|
16
|
+
3. Click **Create A Key**
|
|
17
|
+
4. Give it a name and copy the generated key
|
|
18
|
+
|
|
19
|
+
Your API key will look like: `abc123def456ghi789-us6`
|
|
20
|
+
|
|
21
|
+
The suffix after the final `-` (e.g., `us6`) is your **server prefix** — the examples extract this automatically from the API key.
|
|
22
|
+
|
|
23
|
+
### 2. Set Up Environment
|
|
24
|
+
|
|
25
|
+
Create a `.env` file in `examples/tools/`:
|
|
26
|
+
|
|
27
|
+
```env
|
|
28
|
+
MAILCHIMP_API_KEY=abc123def456ghi789-us6
|
|
29
|
+
OPENAI_API_KEY=sk-your-openai-key-here
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
The `OPENAI_API_KEY` is only required for the LangChain example.
|
|
33
|
+
|
|
34
|
+
### 3. Run Examples
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
# Factory Pattern (simplest, direct API calls)
|
|
38
|
+
pnpm mailchimp:factory
|
|
39
|
+
|
|
40
|
+
# Decorator Pattern (class-based OOP approach)
|
|
41
|
+
pnpm mailchimp:decorator
|
|
42
|
+
|
|
43
|
+
# LangChain Pattern (AI-driven agent with OpenAI)
|
|
44
|
+
pnpm mailchimp:langchain
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## 📚 Examples Overview
|
|
48
|
+
|
|
49
|
+
### 1. Factory Pattern (`mailchimp-factory.ts`)
|
|
50
|
+
|
|
51
|
+
**Best for:** Scripts, quick tests, CLI tools
|
|
52
|
+
|
|
53
|
+
**What it does:**
|
|
54
|
+
- ✅ Direct tool execution with `matimo.execute()`
|
|
55
|
+
- ✅ Loads live audiences and real subscribers from your account
|
|
56
|
+
- ✅ Updates a subscriber's status via PATCH
|
|
57
|
+
- ✅ Creates a draft campaign with a real reply-to address
|
|
58
|
+
- ✅ Simplest implementation
|
|
59
|
+
|
|
60
|
+
**Run it:**
|
|
61
|
+
```bash
|
|
62
|
+
pnpm mailchimp:factory
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
**Key Code:**
|
|
66
|
+
```typescript
|
|
67
|
+
const matimo = await MatimoInstance.init({ autoDiscover: true });
|
|
68
|
+
const SERVER = apiKey.split('-').pop()!;
|
|
69
|
+
|
|
70
|
+
// Get all audiences
|
|
71
|
+
const listsData = await matimo.execute('mailchimp-get-lists', {
|
|
72
|
+
server_prefix: SERVER,
|
|
73
|
+
count: 10,
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
// Get real subscribers from the first audience
|
|
77
|
+
const membersData = await matimo.execute('mailchimp-get-list-members', {
|
|
78
|
+
server_prefix: SERVER,
|
|
79
|
+
list_id: listId,
|
|
80
|
+
count: 5,
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
// Create a draft campaign replying to a real subscriber
|
|
84
|
+
const campaign = await matimo.execute('mailchimp-create-campaign', {
|
|
85
|
+
server_prefix: SERVER,
|
|
86
|
+
type: 'regular',
|
|
87
|
+
list_id: listId,
|
|
88
|
+
subject_line: 'Hello from Matimo!',
|
|
89
|
+
reply_to: contact.email_address,
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
**File:** [mailchimp-factory.ts](mailchimp-factory.ts)
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
### 2. Decorator Pattern (`mailchimp-decorator.ts`)
|
|
98
|
+
|
|
99
|
+
**Best for:** Object-oriented design, class-based applications
|
|
100
|
+
|
|
101
|
+
**What it does:**
|
|
102
|
+
- ✅ Class methods decorated with `@tool`
|
|
103
|
+
- ✅ Automatic tool execution via decorators
|
|
104
|
+
- ✅ Same CRUD flow as factory: audiences → subscribers → update → campaign
|
|
105
|
+
- ✅ OOP-friendly approach
|
|
106
|
+
|
|
107
|
+
**Run it:**
|
|
108
|
+
```bash
|
|
109
|
+
pnpm mailchimp:decorator
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
**Key Code:**
|
|
113
|
+
```typescript
|
|
114
|
+
import { setGlobalMatimoInstance, tool } from 'matimo';
|
|
115
|
+
|
|
116
|
+
const matimo = await MatimoInstance.init({ autoDiscover: true });
|
|
117
|
+
setGlobalMatimoInstance(matimo);
|
|
118
|
+
|
|
119
|
+
class MailchimpAgent {
|
|
120
|
+
@tool('mailchimp-get-lists')
|
|
121
|
+
async getLists(server_prefix: string, count?: number): Promise<unknown> {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
@tool('mailchimp-get-list-members')
|
|
126
|
+
async getListMembers(
|
|
127
|
+
server_prefix: string,
|
|
128
|
+
list_id: string,
|
|
129
|
+
status?: string,
|
|
130
|
+
count?: number
|
|
131
|
+
): Promise<unknown> {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
@tool('mailchimp-create-campaign')
|
|
136
|
+
async createCampaign(
|
|
137
|
+
server_prefix: string,
|
|
138
|
+
type: string,
|
|
139
|
+
list_id: string,
|
|
140
|
+
subject_line: string,
|
|
141
|
+
preview_text?: string,
|
|
142
|
+
title?: string,
|
|
143
|
+
from_name?: string,
|
|
144
|
+
reply_to?: string
|
|
145
|
+
): Promise<unknown> {
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const agent = new MailchimpAgent();
|
|
151
|
+
const lists = await agent.getLists(SERVER, 10);
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
**File:** [mailchimp-decorator.ts](mailchimp-decorator.ts)
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
### 3. LangChain Pattern (`mailchimp-langchain.ts`)
|
|
159
|
+
|
|
160
|
+
**Best for:** AI-driven workflows, autonomous agents, multi-step reasoning
|
|
161
|
+
|
|
162
|
+
**What it does:**
|
|
163
|
+
- ✅ Real AI agent using OpenAI (GPT-4o-mini)
|
|
164
|
+
- ✅ LLM decides which tools to use based on natural language goals
|
|
165
|
+
- ✅ Autonomous execution of multi-step Mailchimp workflows
|
|
166
|
+
- ✅ No tool names in prompts — pure business objectives
|
|
167
|
+
|
|
168
|
+
**Prerequisites:**
|
|
169
|
+
- Requires `OPENAI_API_KEY` set in `.env`
|
|
170
|
+
- Requires `@langchain/openai` and `langchain` dependencies
|
|
171
|
+
|
|
172
|
+
**Run it:**
|
|
173
|
+
```bash
|
|
174
|
+
pnpm mailchimp:langchain
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
**Key Code:**
|
|
178
|
+
```typescript
|
|
179
|
+
import { MatimoInstance, convertToolsToLangChain } from 'matimo';
|
|
180
|
+
import { ChatOpenAI } from '@langchain/openai';
|
|
181
|
+
|
|
182
|
+
const matimo = await MatimoInstance.init({ autoDiscover: true });
|
|
183
|
+
|
|
184
|
+
const mailchimpToolDefs = matimo.listTools().filter((t) => t.name.startsWith('mailchimp-'));
|
|
185
|
+
const langchainTools = await convertToolsToLangChain(mailchimpToolDefs as any[], matimo, {
|
|
186
|
+
MAILCHIMP_API_KEY: apiKey,
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
const model = new ChatOpenAI({ model: 'gpt-4o-mini' });
|
|
190
|
+
const agent = createReactAgent({ llm: model, tools: langchainTools });
|
|
191
|
+
|
|
192
|
+
// Natural language goals — the agent picks the right tools autonomously
|
|
193
|
+
await agent.invoke({ messages: [{ role: 'user', content: 'Show me all my mailing lists' }] });
|
|
194
|
+
await agent.invoke({ messages: [{ role: 'user', content: 'Show me the 5 most recent active subscribers in my first list' }] });
|
|
195
|
+
await agent.invoke({ messages: [{ role: 'user', content: "Create a draft campaign with a descriptive subject line; use the first subscriber's email as reply-to" }] });
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
**Agent Examples:**
|
|
199
|
+
```
|
|
200
|
+
User: "Show me all my mailing lists with names and subscriber counts"
|
|
201
|
+
Agent: [calls mailchimp-get-lists]
|
|
202
|
+
Agent: "You have 2 mailing lists: 'Newsletter' (1,234 subscribers) and 'Updates' (567 subscribers)"
|
|
203
|
+
|
|
204
|
+
User: "Show me the 5 most recent active subscribers in my first list"
|
|
205
|
+
Agent: [calls mailchimp-get-list-members]
|
|
206
|
+
Agent: "Here are 5 recent subscribers: jane@example.com (subscribed), ..."
|
|
207
|
+
|
|
208
|
+
User: "Get my first subscriber and confirm they are still subscribed"
|
|
209
|
+
Agent: [calls mailchimp-get-list-members, then mailchimp-update-list-member]
|
|
210
|
+
Agent: "Confirmed — jane@example.com is subscribed"
|
|
211
|
+
|
|
212
|
+
User: "Create a draft campaign for the newsletter list, use the first subscriber's email as reply-to"
|
|
213
|
+
Agent: [calls mailchimp-create-campaign]
|
|
214
|
+
Agent: "Draft campaign 'Newsletter Update' created (ID: abc123)"
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
**File:** [mailchimp-langchain.ts](mailchimp-langchain.ts)
|
|
218
|
+
|
|
219
|
+
---
|
|
220
|
+
|
|
221
|
+
## 🔧 Supported Operations
|
|
222
|
+
|
|
223
|
+
All examples work with these Mailchimp operations:
|
|
224
|
+
|
|
225
|
+
| Category | Tool Name | Description |
|
|
226
|
+
|----------|-----------|-------------|
|
|
227
|
+
| **Audiences** | `mailchimp-get-lists` | Get all audiences with subscriber counts |
|
|
228
|
+
| **Subscribers** | `mailchimp-get-list-members` | List members with status filter and pagination |
|
|
229
|
+
| **Subscribers** | `mailchimp-add-list-member` | Add a new subscriber to an audience |
|
|
230
|
+
| **Subscribers** | `mailchimp-update-list-member` | Update subscriber status or merge fields (PATCH) |
|
|
231
|
+
| **Subscribers** | `mailchimp-remove-list-member` | Remove a subscriber ⚠️ Requires Approval |
|
|
232
|
+
| **Campaigns** | `mailchimp-create-campaign` | Create a draft email campaign |
|
|
233
|
+
| **Campaigns** | `mailchimp-send-campaign` | Send a campaign ⚠️ Requires Approval |
|
|
234
|
+
|
|
235
|
+
See [packages/mailchimp/README.md](../../packages/mailchimp/README.md) for complete parameter documentation.
|
|
236
|
+
|
|
237
|
+
---
|
|
238
|
+
|
|
239
|
+
## 🔐 Finding Your Server Prefix
|
|
240
|
+
|
|
241
|
+
Your **server prefix** (e.g., `us6`, `us21`) is embedded in your API key:
|
|
242
|
+
|
|
243
|
+
```
|
|
244
|
+
API Key: abc123def456ghi789-us6
|
|
245
|
+
^^^
|
|
246
|
+
server_prefix
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
All examples extract this automatically:
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
const apiKey = process.env.MAILCHIMP_API_KEY!;
|
|
253
|
+
const SERVER = apiKey.split('-').pop()!; // → "us6"
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Pass `SERVER` as the `server_prefix` parameter in every tool call.
|
|
257
|
+
|
|
258
|
+
---
|
|
259
|
+
|
|
260
|
+
## 🛠️ Troubleshooting
|
|
261
|
+
|
|
262
|
+
### "MAILCHIMP_API_KEY not set"
|
|
263
|
+
```bash
|
|
264
|
+
export MAILCHIMP_API_KEY="abc123def456-us6"
|
|
265
|
+
```
|
|
266
|
+
Or add it to `examples/tools/.env`.
|
|
267
|
+
|
|
268
|
+
### "404 Resource Not Found"
|
|
269
|
+
- Wrong `list_id` — retrieve it fresh from `mailchimp-get-lists`
|
|
270
|
+
- Wrong `subscriber_hash` — the examples use the `id` field from `mailchimp-get-list-members`, which is already the MD5 hash
|
|
271
|
+
|
|
272
|
+
### "400 Invalid Resource" on update
|
|
273
|
+
- Mailchimp accounts may require specific merge fields (e.g., ADDRESS sub-fields) that differ per account
|
|
274
|
+
- The `update-list-member` step uses PATCH to update only the fields you provide
|
|
275
|
+
- If the update fails, check your account's audience merge field requirements in Mailchimp → Audience → Settings → Audience fields
|
|
276
|
+
|
|
277
|
+
### "401 Unauthorized"
|
|
278
|
+
- Verify the API key (check for typos or extra spaces)
|
|
279
|
+
- Regenerate it at **Account → Extras → API Keys**
|
|
280
|
+
|
|
281
|
+
### "OpenAI API error" (LangChain example)
|
|
282
|
+
```bash
|
|
283
|
+
export OPENAI_API_KEY="sk-your-openai-key-here"
|
|
284
|
+
```
|
|
285
|
+
Get a key from [platform.openai.com](https://platform.openai.com/account/api-keys).
|
|
286
|
+
|
|
287
|
+
### "Module not found: @langchain/openai"
|
|
288
|
+
```bash
|
|
289
|
+
pnpm install
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
---
|
|
293
|
+
|
|
294
|
+
## 📖 Full Documentation
|
|
295
|
+
|
|
296
|
+
- **Package Docs:** [packages/mailchimp/README.md](../../packages/mailchimp/README.md)
|
|
297
|
+
- **Mailchimp API Reference:** https://mailchimp.com/developer/marketing/api/
|
|
298
|
+
- **Matimo Documentation:** [docs/getting-started/](../../docs/getting-started/)
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
## 🚀 Next Steps
|
|
303
|
+
|
|
304
|
+
1. **Try each example in order:**
|
|
305
|
+
- Start with Factory (simplest)
|
|
306
|
+
- Try Decorator (OOP style)
|
|
307
|
+
- Explore LangChain (AI-driven)
|
|
308
|
+
|
|
309
|
+
2. **Build your own:**
|
|
310
|
+
- Add the `mailchimp-add-list-member` tool to create new subscribers
|
|
311
|
+
- Chain `mailchimp-create-campaign` → `mailchimp-send-campaign` for a full send flow
|
|
312
|
+
- Combine with Slack or Gmail tools for cross-provider workflows
|
|
313
|
+
|
|
314
|
+
3. **Advanced:**
|
|
315
|
+
- Use the LangChain agent for multi-step automated email campaigns
|
|
316
|
+
- Paginate through large audiences with `count` and `offset` parameters
|
|
317
|
+
- Combine Mailchimp tools with other Matimo providers (Slack, Gmail, HubSpot, etc.)
|
|
318
|
+
|
|
319
|
+
---
|
|
320
|
+
|
|
321
|
+
**Questions?** See [CONTRIBUTING.md](../../CONTRIBUTING.md) or review the Matimo core documentation.
|