rcrewai 0.1.0 → 0.2.0
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.
- checksums.yaml +4 -4
- data/docs/api/agent.md +429 -0
- data/docs/api/task.md +494 -0
- data/docs/examples/api-integration.md +829 -0
- data/docs/examples/async-execution.md +893 -0
- data/docs/examples/code-review-crew.md +660 -0
- data/docs/examples/content-marketing-pipeline.md +681 -0
- data/docs/examples/custom-tools.md +1224 -0
- data/docs/examples/customer-support.md +717 -0
- data/docs/examples/data-analysis-team.md +677 -0
- data/docs/examples/database-operations.md +1298 -0
- data/docs/examples/ecommerce-operations.md +990 -0
- data/docs/examples/financial-analysis.md +857 -0
- data/docs/examples/hierarchical-crew.md +479 -0
- data/docs/examples/product-development.md +688 -0
- data/docs/examples/production-ready-crew.md +384 -408
- data/docs/examples/research-development.md +1225 -0
- data/docs/examples/social-media.md +1073 -0
- data/docs/examples/task-automation.md +527 -0
- data/docs/examples/tool-composition.md +1075 -0
- data/docs/examples/web-scraping.md +1201 -0
- data/docs/tutorials/advanced-agents.md +1014 -0
- data/docs/tutorials/custom-tools.md +1242 -0
- data/docs/tutorials/deployment.md +1836 -0
- data/docs/tutorials/index.md +184 -0
- data/docs/tutorials/multiple-crews.md +1692 -0
- data/lib/rcrewai/llm_clients/anthropic.rb +1 -1
- data/lib/rcrewai/version.rb +1 -1
- metadata +26 -2
@@ -0,0 +1,829 @@
|
|
1
|
+
---
|
2
|
+
layout: example
|
3
|
+
title: API Integration Example
|
4
|
+
description: Comprehensive API integration patterns with external services, error handling, and data synchronization
|
5
|
+
---
|
6
|
+
|
7
|
+
# API Integration Example
|
8
|
+
|
9
|
+
This example demonstrates how to integrate RCrewAI crews with external APIs and services. We'll build a comprehensive system that handles API authentication, data synchronization, error handling, and service orchestration across multiple external platforms.
|
10
|
+
|
11
|
+
## Overview
|
12
|
+
|
13
|
+
Our API integration system includes:
|
14
|
+
- **CRM Integration** - Sync customer data with Salesforce/HubSpot
|
15
|
+
- **Payment Processing** - Handle transactions with Stripe/PayPal
|
16
|
+
- **Email Marketing** - Automate campaigns with Mailchimp/SendGrid
|
17
|
+
- **Analytics Integration** - Push data to Google Analytics/Mixpanel
|
18
|
+
- **Social Media APIs** - Manage posts across Twitter/LinkedIn/Facebook
|
19
|
+
|
20
|
+
## Complete Implementation
|
21
|
+
|
22
|
+
```ruby
|
23
|
+
require 'rcrewai'
|
24
|
+
require 'faraday'
|
25
|
+
require 'json'
|
26
|
+
require 'base64'
|
27
|
+
|
28
|
+
# Configure RCrewAI for API integration tasks
|
29
|
+
RCrewAI.configure do |config|
|
30
|
+
config.llm_provider = :openai
|
31
|
+
config.temperature = 0.3 # Lower temperature for precise API operations
|
32
|
+
end
|
33
|
+
|
34
|
+
# ===== CUSTOM API INTEGRATION TOOLS =====
|
35
|
+
|
36
|
+
# Generic REST API Tool
|
37
|
+
class RestAPITool < RCrewAI::Tools::Base
|
38
|
+
def initialize(**options)
|
39
|
+
super
|
40
|
+
@name = 'rest_api'
|
41
|
+
@description = 'Make REST API calls with authentication and error handling'
|
42
|
+
@base_url = options[:base_url]
|
43
|
+
@api_key = options[:api_key]
|
44
|
+
@auth_type = options[:auth_type] || :bearer
|
45
|
+
@timeout = options[:timeout] || 30
|
46
|
+
setup_client
|
47
|
+
end
|
48
|
+
|
49
|
+
def execute(**params)
|
50
|
+
validate_params!(params, required: [:method, :endpoint], optional: [:data, :headers])
|
51
|
+
|
52
|
+
method = params[:method].to_s.downcase.to_sym
|
53
|
+
endpoint = params[:endpoint]
|
54
|
+
data = params[:data]
|
55
|
+
headers = params[:headers] || {}
|
56
|
+
|
57
|
+
# Add authentication
|
58
|
+
headers = add_authentication(headers)
|
59
|
+
|
60
|
+
# Make request with retry logic
|
61
|
+
response = make_request_with_retry(method, endpoint, data, headers)
|
62
|
+
|
63
|
+
format_response(response)
|
64
|
+
rescue => e
|
65
|
+
handle_api_error(e)
|
66
|
+
end
|
67
|
+
|
68
|
+
private
|
69
|
+
|
70
|
+
def setup_client
|
71
|
+
@client = Faraday.new(url: @base_url) do |f|
|
72
|
+
f.request :json
|
73
|
+
f.response :json
|
74
|
+
f.adapter Faraday.default_adapter
|
75
|
+
f.options.timeout = @timeout
|
76
|
+
end
|
77
|
+
end
|
78
|
+
|
79
|
+
def add_authentication(headers)
|
80
|
+
case @auth_type
|
81
|
+
when :bearer
|
82
|
+
headers['Authorization'] = "Bearer #{@api_key}" if @api_key
|
83
|
+
when :basic
|
84
|
+
headers['Authorization'] = "Basic #{Base64.encode64(@api_key)}" if @api_key
|
85
|
+
when :header
|
86
|
+
headers['X-API-Key'] = @api_key if @api_key
|
87
|
+
end
|
88
|
+
headers
|
89
|
+
end
|
90
|
+
|
91
|
+
def make_request_with_retry(method, endpoint, data, headers, retries = 3)
|
92
|
+
response = @client.send(method, endpoint, data, headers)
|
93
|
+
|
94
|
+
# Handle rate limiting
|
95
|
+
if response.status == 429 && retries > 0
|
96
|
+
sleep_time = response.headers['retry-after']&.to_i || 1
|
97
|
+
sleep(sleep_time)
|
98
|
+
return make_request_with_retry(method, endpoint, data, headers, retries - 1)
|
99
|
+
end
|
100
|
+
|
101
|
+
response
|
102
|
+
rescue Faraday::Error => e
|
103
|
+
if retries > 0
|
104
|
+
sleep(2 ** (3 - retries)) # Exponential backoff
|
105
|
+
make_request_with_retry(method, endpoint, data, headers, retries - 1)
|
106
|
+
else
|
107
|
+
raise
|
108
|
+
end
|
109
|
+
end
|
110
|
+
|
111
|
+
def format_response(response)
|
112
|
+
{
|
113
|
+
status: response.status,
|
114
|
+
success: response.success?,
|
115
|
+
data: response.body,
|
116
|
+
headers: response.headers.to_h
|
117
|
+
}.to_json
|
118
|
+
end
|
119
|
+
|
120
|
+
def handle_api_error(error)
|
121
|
+
"API Error: #{error.class} - #{error.message}"
|
122
|
+
end
|
123
|
+
end
|
124
|
+
|
125
|
+
# CRM Integration Tool
|
126
|
+
class CRMIntegrationTool < RestAPITool
|
127
|
+
def initialize(**options)
|
128
|
+
super(
|
129
|
+
base_url: options[:crm_url] || 'https://api.hubspot.com',
|
130
|
+
api_key: options[:api_key],
|
131
|
+
auth_type: :bearer
|
132
|
+
)
|
133
|
+
@name = 'crm_integration'
|
134
|
+
@description = 'Integrate with CRM systems for customer data management'
|
135
|
+
end
|
136
|
+
|
137
|
+
def execute(**params)
|
138
|
+
action = params[:action]
|
139
|
+
|
140
|
+
case action
|
141
|
+
when 'create_contact'
|
142
|
+
create_contact(params[:contact_data])
|
143
|
+
when 'update_contact'
|
144
|
+
update_contact(params[:contact_id], params[:contact_data])
|
145
|
+
when 'get_contact'
|
146
|
+
get_contact(params[:contact_id])
|
147
|
+
when 'sync_contacts'
|
148
|
+
sync_contacts(params[:contacts])
|
149
|
+
else
|
150
|
+
super
|
151
|
+
end
|
152
|
+
end
|
153
|
+
|
154
|
+
private
|
155
|
+
|
156
|
+
def create_contact(contact_data)
|
157
|
+
super(
|
158
|
+
method: 'post',
|
159
|
+
endpoint: '/crm/v3/objects/contacts',
|
160
|
+
data: { properties: contact_data }
|
161
|
+
)
|
162
|
+
end
|
163
|
+
|
164
|
+
def update_contact(contact_id, contact_data)
|
165
|
+
super(
|
166
|
+
method: 'patch',
|
167
|
+
endpoint: "/crm/v3/objects/contacts/#{contact_id}",
|
168
|
+
data: { properties: contact_data }
|
169
|
+
)
|
170
|
+
end
|
171
|
+
|
172
|
+
def get_contact(contact_id)
|
173
|
+
super(
|
174
|
+
method: 'get',
|
175
|
+
endpoint: "/crm/v3/objects/contacts/#{contact_id}"
|
176
|
+
)
|
177
|
+
end
|
178
|
+
|
179
|
+
def sync_contacts(contacts)
|
180
|
+
results = []
|
181
|
+
contacts.each do |contact|
|
182
|
+
result = if contact[:id]
|
183
|
+
update_contact(contact[:id], contact[:data])
|
184
|
+
else
|
185
|
+
create_contact(contact[:data])
|
186
|
+
end
|
187
|
+
results << result
|
188
|
+
end
|
189
|
+
results.to_json
|
190
|
+
end
|
191
|
+
end
|
192
|
+
|
193
|
+
# Payment Integration Tool
|
194
|
+
class PaymentIntegrationTool < RestAPITool
|
195
|
+
def initialize(**options)
|
196
|
+
super(
|
197
|
+
base_url: 'https://api.stripe.com/v1',
|
198
|
+
api_key: options[:stripe_key],
|
199
|
+
auth_type: :basic
|
200
|
+
)
|
201
|
+
@name = 'payment_integration'
|
202
|
+
@description = 'Process payments and manage transactions'
|
203
|
+
end
|
204
|
+
|
205
|
+
def execute(**params)
|
206
|
+
action = params[:action]
|
207
|
+
|
208
|
+
case action
|
209
|
+
when 'create_payment_intent'
|
210
|
+
create_payment_intent(params[:amount], params[:currency], params[:metadata])
|
211
|
+
when 'capture_payment'
|
212
|
+
capture_payment(params[:payment_intent_id])
|
213
|
+
when 'refund_payment'
|
214
|
+
refund_payment(params[:payment_intent_id], params[:amount])
|
215
|
+
when 'get_customer'
|
216
|
+
get_customer(params[:customer_id])
|
217
|
+
else
|
218
|
+
super
|
219
|
+
end
|
220
|
+
end
|
221
|
+
|
222
|
+
private
|
223
|
+
|
224
|
+
def create_payment_intent(amount, currency, metadata = {})
|
225
|
+
super(
|
226
|
+
method: 'post',
|
227
|
+
endpoint: '/payment_intents',
|
228
|
+
data: {
|
229
|
+
amount: amount,
|
230
|
+
currency: currency,
|
231
|
+
metadata: metadata,
|
232
|
+
automatic_payment_methods: { enabled: true }
|
233
|
+
}
|
234
|
+
)
|
235
|
+
end
|
236
|
+
|
237
|
+
def capture_payment(payment_intent_id)
|
238
|
+
super(
|
239
|
+
method: 'post',
|
240
|
+
endpoint: "/payment_intents/#{payment_intent_id}/capture"
|
241
|
+
)
|
242
|
+
end
|
243
|
+
|
244
|
+
def refund_payment(payment_intent_id, amount = nil)
|
245
|
+
data = { payment_intent: payment_intent_id }
|
246
|
+
data[:amount] = amount if amount
|
247
|
+
|
248
|
+
super(
|
249
|
+
method: 'post',
|
250
|
+
endpoint: '/refunds',
|
251
|
+
data: data
|
252
|
+
)
|
253
|
+
end
|
254
|
+
end
|
255
|
+
|
256
|
+
# ===== API INTEGRATION AGENTS =====
|
257
|
+
|
258
|
+
# API Orchestration Manager
|
259
|
+
api_manager = RCrewAI::Agent.new(
|
260
|
+
name: "api_orchestrator",
|
261
|
+
role: "API Integration Manager",
|
262
|
+
goal: "Coordinate and orchestrate multiple API integrations efficiently and reliably",
|
263
|
+
backstory: "You are an experienced integration architect who excels at managing complex API workflows, handling errors gracefully, and ensuring data consistency across systems.",
|
264
|
+
tools: [
|
265
|
+
RCrewAI::Tools::FileReader.new,
|
266
|
+
RCrewAI::Tools::FileWriter.new
|
267
|
+
],
|
268
|
+
verbose: true
|
269
|
+
)
|
270
|
+
|
271
|
+
# CRM Synchronization Specialist
|
272
|
+
crm_specialist = RCrewAI::Agent.new(
|
273
|
+
name: "crm_sync_specialist",
|
274
|
+
role: "CRM Integration Specialist",
|
275
|
+
goal: "Maintain accurate and up-to-date customer data across CRM systems",
|
276
|
+
backstory: "You are a CRM expert who understands customer data management, deduplication, and synchronization best practices. You ensure data integrity across all customer touchpoints.",
|
277
|
+
tools: [
|
278
|
+
CRMIntegrationTool.new(api_key: ENV['HUBSPOT_API_KEY']),
|
279
|
+
RCrewAI::Tools::FileReader.new,
|
280
|
+
RCrewAI::Tools::FileWriter.new
|
281
|
+
],
|
282
|
+
verbose: true
|
283
|
+
)
|
284
|
+
|
285
|
+
# Payment Processing Specialist
|
286
|
+
payment_specialist = RCrewAI::Agent.new(
|
287
|
+
name: "payment_processor",
|
288
|
+
role: "Payment Integration Specialist",
|
289
|
+
goal: "Handle secure payment processing and transaction management",
|
290
|
+
backstory: "You are a payment processing expert who understands PCI compliance, transaction security, and financial data handling. You ensure all payments are processed accurately and securely.",
|
291
|
+
tools: [
|
292
|
+
PaymentIntegrationTool.new(stripe_key: ENV['STRIPE_API_KEY']),
|
293
|
+
RCrewAI::Tools::FileWriter.new
|
294
|
+
],
|
295
|
+
verbose: true
|
296
|
+
)
|
297
|
+
|
298
|
+
# Email Marketing Specialist
|
299
|
+
email_specialist = RCrewAI::Agent.new(
|
300
|
+
name: "email_marketing_specialist",
|
301
|
+
role: "Email Marketing Integration Expert",
|
302
|
+
goal: "Automate email marketing campaigns and manage subscriber lists",
|
303
|
+
backstory: "You are an email marketing expert who understands automation workflows, segmentation, and deliverability best practices. You create effective email campaigns that drive engagement.",
|
304
|
+
tools: [
|
305
|
+
RestAPITool.new(
|
306
|
+
base_url: 'https://api.mailchimp.com/3.0',
|
307
|
+
api_key: ENV['MAILCHIMP_API_KEY'],
|
308
|
+
auth_type: :basic
|
309
|
+
),
|
310
|
+
RCrewAI::Tools::FileWriter.new
|
311
|
+
],
|
312
|
+
verbose: true
|
313
|
+
)
|
314
|
+
|
315
|
+
# Analytics Integration Specialist
|
316
|
+
analytics_specialist = RCrewAI::Agent.new(
|
317
|
+
name: "analytics_integrator",
|
318
|
+
role: "Analytics Integration Specialist",
|
319
|
+
goal: "Track events and sync data with analytics platforms",
|
320
|
+
backstory: "You are an analytics expert who understands data tracking, event management, and analytics implementation. You ensure all user interactions are properly tracked and analyzed.",
|
321
|
+
tools: [
|
322
|
+
RestAPITool.new(
|
323
|
+
base_url: 'https://www.googleapis.com/analytics/v3',
|
324
|
+
api_key: ENV['GOOGLE_ANALYTICS_KEY'],
|
325
|
+
auth_type: :bearer
|
326
|
+
),
|
327
|
+
RCrewAI::Tools::FileWriter.new
|
328
|
+
],
|
329
|
+
verbose: true
|
330
|
+
)
|
331
|
+
|
332
|
+
# Create API integration crew
|
333
|
+
integration_crew = RCrewAI::Crew.new("api_integration_crew")
|
334
|
+
|
335
|
+
# Add agents to crew
|
336
|
+
integration_crew.add_agent(api_manager)
|
337
|
+
integration_crew.add_agent(crm_specialist)
|
338
|
+
integration_crew.add_agent(payment_specialist)
|
339
|
+
integration_crew.add_agent(email_specialist)
|
340
|
+
integration_crew.add_agent(analytics_specialist)
|
341
|
+
|
342
|
+
# ===== API INTEGRATION TASKS =====
|
343
|
+
|
344
|
+
# CRM Data Synchronization Task
|
345
|
+
crm_sync_task = RCrewAI::Task.new(
|
346
|
+
name: "crm_data_synchronization",
|
347
|
+
description: "Synchronize customer data with CRM system. Update existing contacts, create new contacts for leads, and ensure data consistency. Handle deduplication and data validation. Create comprehensive sync report with success/failure statistics.",
|
348
|
+
expected_output: "CRM synchronization report with updated contact counts, new contact creation results, and data quality metrics",
|
349
|
+
agent: crm_specialist,
|
350
|
+
async: true
|
351
|
+
)
|
352
|
+
|
353
|
+
# Payment Processing Task
|
354
|
+
payment_processing_task = RCrewAI::Task.new(
|
355
|
+
name: "payment_transaction_processing",
|
356
|
+
description: "Process pending payment transactions securely. Handle payment intents, capture authorized payments, process refunds as needed, and update transaction records. Ensure PCI compliance and generate payment reports.",
|
357
|
+
expected_output: "Payment processing report with transaction summaries, success rates, and security compliance confirmation",
|
358
|
+
agent: payment_specialist,
|
359
|
+
async: true
|
360
|
+
)
|
361
|
+
|
362
|
+
# Email Campaign Automation Task
|
363
|
+
email_automation_task = RCrewAI::Task.new(
|
364
|
+
name: "email_campaign_automation",
|
365
|
+
description: "Set up and execute automated email marketing campaigns. Create subscriber segments, design email sequences, schedule campaigns, and track performance metrics. Ensure compliance with email marketing regulations.",
|
366
|
+
expected_output: "Email automation setup report with campaign configurations, subscriber statistics, and performance tracking setup",
|
367
|
+
agent: email_specialist,
|
368
|
+
async: true
|
369
|
+
)
|
370
|
+
|
371
|
+
# Analytics Event Tracking Task
|
372
|
+
analytics_task = RCrewAI::Task.new(
|
373
|
+
name: "analytics_event_tracking",
|
374
|
+
description: "Implement comprehensive event tracking across all customer touchpoints. Set up conversion tracking, goal configurations, and custom events. Push relevant data to analytics platforms for reporting and analysis.",
|
375
|
+
expected_output: "Analytics implementation report with event tracking setup, conversion goals, and data validation results",
|
376
|
+
agent: analytics_specialist,
|
377
|
+
async: true
|
378
|
+
)
|
379
|
+
|
380
|
+
# Integration Orchestration Task
|
381
|
+
orchestration_task = RCrewAI::Task.new(
|
382
|
+
name: "api_integration_orchestration",
|
383
|
+
description: "Coordinate all API integrations to ensure data consistency and workflow efficiency. Monitor integration health, handle cross-system dependencies, and provide comprehensive integration status reporting.",
|
384
|
+
expected_output: "Integration orchestration report with system health status, data flow validation, and performance metrics",
|
385
|
+
agent: api_manager,
|
386
|
+
context: [crm_sync_task, payment_processing_task, email_automation_task, analytics_task]
|
387
|
+
)
|
388
|
+
|
389
|
+
# Add tasks to crew
|
390
|
+
integration_crew.add_task(crm_sync_task)
|
391
|
+
integration_crew.add_task(payment_processing_task)
|
392
|
+
integration_crew.add_task(email_automation_task)
|
393
|
+
integration_crew.add_task(analytics_task)
|
394
|
+
integration_crew.add_task(orchestration_task)
|
395
|
+
|
396
|
+
# ===== SAMPLE DATA FOR INTEGRATION =====
|
397
|
+
|
398
|
+
puts "🔌 Setting Up API Integration Test Data"
|
399
|
+
puts "="*50
|
400
|
+
|
401
|
+
# Sample customer data for CRM sync
|
402
|
+
customer_data = [
|
403
|
+
{
|
404
|
+
id: nil, # New contact
|
405
|
+
data: {
|
406
|
+
email: "john.doe@example.com",
|
407
|
+
firstname: "John",
|
408
|
+
lastname: "Doe",
|
409
|
+
company: "Tech Corp",
|
410
|
+
phone: "+1-555-0101",
|
411
|
+
lifecycle_stage: "lead"
|
412
|
+
}
|
413
|
+
},
|
414
|
+
{
|
415
|
+
id: "12345", # Existing contact to update
|
416
|
+
data: {
|
417
|
+
email: "jane.smith@example.com",
|
418
|
+
firstname: "Jane",
|
419
|
+
lastname: "Smith",
|
420
|
+
company: "Innovation Inc",
|
421
|
+
lifecycle_stage: "customer"
|
422
|
+
}
|
423
|
+
}
|
424
|
+
]
|
425
|
+
|
426
|
+
# Sample payment transactions
|
427
|
+
payment_transactions = [
|
428
|
+
{
|
429
|
+
amount: 2999, # $29.99 in cents
|
430
|
+
currency: "usd",
|
431
|
+
customer_email: "john.doe@example.com",
|
432
|
+
description: "Premium subscription",
|
433
|
+
metadata: { plan: "premium", duration: "monthly" }
|
434
|
+
},
|
435
|
+
{
|
436
|
+
amount: 9999, # $99.99 in cents
|
437
|
+
currency: "usd",
|
438
|
+
customer_email: "jane.smith@example.com",
|
439
|
+
description: "Annual subscription",
|
440
|
+
metadata: { plan: "professional", duration: "annual" }
|
441
|
+
}
|
442
|
+
]
|
443
|
+
|
444
|
+
# Sample email campaigns
|
445
|
+
email_campaigns = [
|
446
|
+
{
|
447
|
+
type: "welcome_series",
|
448
|
+
list_name: "new_subscribers",
|
449
|
+
subject_line: "Welcome to Our Platform!",
|
450
|
+
template: "welcome_template_v2",
|
451
|
+
automation_trigger: "subscription_confirmed"
|
452
|
+
},
|
453
|
+
{
|
454
|
+
type: "product_announcement",
|
455
|
+
list_name: "active_customers",
|
456
|
+
subject_line: "Exciting New Features Available Now",
|
457
|
+
template: "product_update_template",
|
458
|
+
send_time: "2024-01-15T10:00:00Z"
|
459
|
+
}
|
460
|
+
]
|
461
|
+
|
462
|
+
# Sample analytics events
|
463
|
+
analytics_events = [
|
464
|
+
{
|
465
|
+
event_category: "subscription",
|
466
|
+
event_action: "upgrade",
|
467
|
+
event_label: "premium_plan",
|
468
|
+
custom_dimensions: { user_segment: "power_user", trial_length: "14_days" }
|
469
|
+
},
|
470
|
+
{
|
471
|
+
event_category: "feature_usage",
|
472
|
+
event_action: "api_call",
|
473
|
+
event_label: "data_export",
|
474
|
+
custom_dimensions: { api_version: "v2", export_format: "json" }
|
475
|
+
}
|
476
|
+
]
|
477
|
+
|
478
|
+
# Save test data
|
479
|
+
File.write("integration_test_data.json", JSON.pretty_generate({
|
480
|
+
customers: customer_data,
|
481
|
+
payments: payment_transactions,
|
482
|
+
email_campaigns: email_campaigns,
|
483
|
+
analytics_events: analytics_events
|
484
|
+
}))
|
485
|
+
|
486
|
+
puts "✅ Test data prepared:"
|
487
|
+
puts " - 2 customer records for CRM sync"
|
488
|
+
puts " - 2 payment transactions to process"
|
489
|
+
puts " - 2 email campaigns to set up"
|
490
|
+
puts " - 2 analytics events to track"
|
491
|
+
|
492
|
+
# ===== EXECUTE API INTEGRATIONS =====
|
493
|
+
|
494
|
+
puts "\n🚀 Starting API Integration Workflow"
|
495
|
+
puts "="*50
|
496
|
+
|
497
|
+
# Execute the integration crew
|
498
|
+
results = integration_crew.execute
|
499
|
+
|
500
|
+
# ===== INTEGRATION RESULTS =====
|
501
|
+
|
502
|
+
puts "\n📊 API INTEGRATION RESULTS"
|
503
|
+
puts "="*50
|
504
|
+
|
505
|
+
puts "Integration Success Rate: #{results[:success_rate]}%"
|
506
|
+
puts "Total Integration Tasks: #{results[:total_tasks]}"
|
507
|
+
puts "Completed Integrations: #{results[:completed_tasks]}"
|
508
|
+
puts "Integration Status: #{results[:success_rate] >= 80 ? 'SUCCESS' : 'NEEDS ATTENTION'}"
|
509
|
+
|
510
|
+
integration_categories = {
|
511
|
+
"crm_data_synchronization" => "🔄 CRM Synchronization",
|
512
|
+
"payment_transaction_processing" => "💳 Payment Processing",
|
513
|
+
"email_campaign_automation" => "📧 Email Automation",
|
514
|
+
"analytics_event_tracking" => "📈 Analytics Tracking",
|
515
|
+
"api_integration_orchestration" => "🎯 Integration Orchestration"
|
516
|
+
}
|
517
|
+
|
518
|
+
puts "\n📋 INTEGRATION BREAKDOWN:"
|
519
|
+
puts "-"*40
|
520
|
+
|
521
|
+
results[:results].each do |integration_result|
|
522
|
+
task_name = integration_result[:task].name
|
523
|
+
category_name = integration_categories[task_name] || task_name
|
524
|
+
status_emoji = integration_result[:status] == :completed ? "✅" : "❌"
|
525
|
+
|
526
|
+
puts "#{status_emoji} #{category_name}"
|
527
|
+
puts " Specialist: #{integration_result[:assigned_agent] || integration_result[:task].agent.name}"
|
528
|
+
puts " Status: #{integration_result[:status]}"
|
529
|
+
|
530
|
+
if integration_result[:status] == :completed
|
531
|
+
puts " Integration: Successfully completed"
|
532
|
+
else
|
533
|
+
puts " Error: #{integration_result[:error]&.message}"
|
534
|
+
end
|
535
|
+
puts
|
536
|
+
end
|
537
|
+
|
538
|
+
# ===== SAVE INTEGRATION REPORTS =====
|
539
|
+
|
540
|
+
puts "\n💾 GENERATING INTEGRATION REPORTS"
|
541
|
+
puts "-"*40
|
542
|
+
|
543
|
+
completed_integrations = results[:results].select { |r| r[:status] == :completed }
|
544
|
+
|
545
|
+
# Create integration reports directory
|
546
|
+
integration_dir = "api_integration_#{Date.today.strftime('%Y%m%d')}"
|
547
|
+
Dir.mkdir(integration_dir) unless Dir.exist?(integration_dir)
|
548
|
+
|
549
|
+
completed_integrations.each do |integration_result|
|
550
|
+
task_name = integration_result[:task].name
|
551
|
+
integration_content = integration_result[:result]
|
552
|
+
|
553
|
+
filename = "#{integration_dir}/#{task_name}_report.md"
|
554
|
+
|
555
|
+
formatted_report = <<~REPORT
|
556
|
+
# #{integration_categories[task_name] || task_name.split('_').map(&:capitalize).join(' ')} Report
|
557
|
+
|
558
|
+
**Integration Specialist:** #{integration_result[:assigned_agent] || integration_result[:task].agent.name}
|
559
|
+
**Integration Date:** #{Time.now.strftime('%B %d, %Y')}
|
560
|
+
**Status:** #{integration_result[:status]}
|
561
|
+
|
562
|
+
---
|
563
|
+
|
564
|
+
#{integration_content}
|
565
|
+
|
566
|
+
---
|
567
|
+
|
568
|
+
**Integration Details:**
|
569
|
+
- API Endpoints: Multiple external services
|
570
|
+
- Authentication: Secure token-based authentication
|
571
|
+
- Error Handling: Comprehensive retry logic and fallback procedures
|
572
|
+
- Data Validation: Input/output validation and sanitization
|
573
|
+
|
574
|
+
*Generated by RCrewAI API Integration System*
|
575
|
+
REPORT
|
576
|
+
|
577
|
+
File.write(filename, formatted_report)
|
578
|
+
puts " ✅ #{File.basename(filename)}"
|
579
|
+
end
|
580
|
+
|
581
|
+
# ===== INTEGRATION HEALTH DASHBOARD =====
|
582
|
+
|
583
|
+
health_dashboard = <<~DASHBOARD
|
584
|
+
# API Integration Health Dashboard
|
585
|
+
|
586
|
+
**Last Updated:** #{Time.now.strftime('%Y-%m-%d %H:%M:%S')}
|
587
|
+
**Integration Success Rate:** #{results[:success_rate]}%
|
588
|
+
|
589
|
+
## System Status Overview
|
590
|
+
|
591
|
+
### External Service Connectivity
|
592
|
+
- **CRM (HubSpot):** #{completed_integrations.find { |i| i[:task].name.include?('crm') } ? '🟢 Connected' : '🔴 Disconnected'}
|
593
|
+
- **Payments (Stripe):** #{completed_integrations.find { |i| i[:task].name.include?('payment') } ? '🟢 Connected' : '🔴 Disconnected'}
|
594
|
+
- **Email (Mailchimp):** #{completed_integrations.find { |i| i[:task].name.include?('email') } ? '🟢 Connected' : '🔴 Disconnected'}
|
595
|
+
- **Analytics (Google):** #{completed_integrations.find { |i| i[:task].name.include?('analytics') } ? '🟢 Connected' : '🔴 Disconnected'}
|
596
|
+
|
597
|
+
### Data Synchronization Status
|
598
|
+
- **Customer Records:** In Sync (Last sync: #{Time.now.strftime('%H:%M')})
|
599
|
+
- **Payment Transactions:** Processing (Queue: 0 pending)
|
600
|
+
- **Email Campaigns:** Active (2 campaigns running)
|
601
|
+
- **Analytics Events:** Tracking (Real-time processing)
|
602
|
+
|
603
|
+
### Performance Metrics
|
604
|
+
- **API Response Times:** Average 245ms
|
605
|
+
- **Success Rate (24h):** 98.5%
|
606
|
+
- **Error Rate (24h):** 1.5%
|
607
|
+
- **Data Throughput:** 1,250 records/hour
|
608
|
+
|
609
|
+
## Integration Workflow Status
|
610
|
+
|
611
|
+
### Customer Journey Integration
|
612
|
+
```
|
613
|
+
Lead Capture → CRM → Payment → Email → Analytics
|
614
|
+
✅ ✅ ✅ ✅ ✅
|
615
|
+
```
|
616
|
+
|
617
|
+
### Data Flow Validation
|
618
|
+
- **Source Systems:** Web forms, mobile app, customer service
|
619
|
+
- **Processing Pipeline:** Data validation → Transformation → Distribution
|
620
|
+
- **Destination Systems:** CRM, payment processor, email platform, analytics
|
621
|
+
- **Data Quality:** 99.2% clean data rate
|
622
|
+
|
623
|
+
## Alert Configuration
|
624
|
+
|
625
|
+
### Critical Alerts (Immediate Action Required)
|
626
|
+
- API response time > 5 seconds
|
627
|
+
- Error rate > 5% for any service
|
628
|
+
- Payment processing failures
|
629
|
+
- Data synchronization delays > 1 hour
|
630
|
+
|
631
|
+
### Warning Alerts (Monitor Closely)
|
632
|
+
- API response time > 2 seconds
|
633
|
+
- Error rate > 2% for any service
|
634
|
+
- Email deliverability < 95%
|
635
|
+
- Analytics data gaps
|
636
|
+
|
637
|
+
## Recovery Procedures
|
638
|
+
|
639
|
+
### Automatic Recovery
|
640
|
+
- **Retry Logic:** 3 attempts with exponential backoff
|
641
|
+
- **Circuit Breaker:** Auto-disable failing services temporarily
|
642
|
+
- **Fallback Data:** Queue data for later processing
|
643
|
+
- **Health Checks:** Every 30 seconds with auto-recovery
|
644
|
+
|
645
|
+
### Manual Intervention Required
|
646
|
+
- **Authentication Failures:** Update API credentials
|
647
|
+
- **Service Outages:** Contact vendor support
|
648
|
+
- **Data Corruption:** Execute data validation and cleanup
|
649
|
+
- **Integration Changes:** Update configuration and test
|
650
|
+
|
651
|
+
## Maintenance Windows
|
652
|
+
|
653
|
+
### Scheduled Maintenance
|
654
|
+
- **HubSpot:** First Sunday of month, 2:00-4:00 AM EST
|
655
|
+
- **Stripe:** Second Tuesday of month, 1:00-2:00 AM EST
|
656
|
+
- **Mailchimp:** Third Wednesday of month, 3:00-4:00 AM EST
|
657
|
+
- **Google Analytics:** Ongoing (no scheduled downtime)
|
658
|
+
|
659
|
+
### Emergency Procedures
|
660
|
+
1. **Service Outage Detection:** Automated alerts via PagerDuty
|
661
|
+
2. **Incident Response:** 15-minute response time SLA
|
662
|
+
3. **Communication:** Status page updates and customer notifications
|
663
|
+
4. **Resolution:** Escalation procedures and vendor coordination
|
664
|
+
DASHBOARD
|
665
|
+
|
666
|
+
File.write("#{integration_dir}/integration_health_dashboard.md", health_dashboard)
|
667
|
+
puts " ✅ integration_health_dashboard.md"
|
668
|
+
|
669
|
+
# ===== INTEGRATION SUMMARY =====
|
670
|
+
|
671
|
+
integration_summary = <<~SUMMARY
|
672
|
+
# API Integration Summary Report
|
673
|
+
|
674
|
+
**Integration Date:** #{Time.now.strftime('%B %d, %Y')}
|
675
|
+
**Total Services Integrated:** #{completed_integrations.length}
|
676
|
+
**Success Rate:** #{results[:success_rate]}%
|
677
|
+
|
678
|
+
## Integration Achievements
|
679
|
+
|
680
|
+
✅ **CRM Integration:** Customer data synchronized with HubSpot
|
681
|
+
✅ **Payment Processing:** Secure transaction handling with Stripe
|
682
|
+
✅ **Email Automation:** Marketing campaigns configured with Mailchimp
|
683
|
+
✅ **Analytics Tracking:** Event tracking implemented with Google Analytics
|
684
|
+
✅ **Orchestration:** Cross-system coordination and monitoring established
|
685
|
+
|
686
|
+
## Business Impact
|
687
|
+
|
688
|
+
### Automation Benefits
|
689
|
+
- **Time Savings:** 15-20 hours/week of manual data entry eliminated
|
690
|
+
- **Data Accuracy:** 99.2% data quality through automated validation
|
691
|
+
- **Response Time:** Customer interactions processed in under 2 minutes
|
692
|
+
- **Scalability:** System handles 10x current transaction volume
|
693
|
+
|
694
|
+
### Revenue Impact
|
695
|
+
- **Faster Sales Cycles:** 30% reduction in lead-to-customer time
|
696
|
+
- **Improved Conversion:** 25% increase in email campaign effectiveness
|
697
|
+
- **Payment Success:** 98.5% payment processing success rate
|
698
|
+
- **Customer Retention:** Enhanced data insights drive better retention
|
699
|
+
|
700
|
+
## Technical Architecture
|
701
|
+
|
702
|
+
### Integration Patterns
|
703
|
+
- **Event-Driven:** Real-time data synchronization
|
704
|
+
- **Microservices:** Loosely coupled service integration
|
705
|
+
- **API Gateway:** Centralized API management and security
|
706
|
+
- **Queue-Based:** Reliable message processing with retry logic
|
707
|
+
|
708
|
+
### Security Implementation
|
709
|
+
- **Authentication:** OAuth 2.0 and API key management
|
710
|
+
- **Encryption:** TLS 1.3 for data in transit
|
711
|
+
- **Access Control:** Role-based permissions and audit trails
|
712
|
+
- **Compliance:** PCI DSS, GDPR, and SOC 2 adherence
|
713
|
+
|
714
|
+
## Operational Excellence
|
715
|
+
|
716
|
+
### Monitoring and Alerting
|
717
|
+
- **Real-time Dashboards:** System health and performance metrics
|
718
|
+
- **Automated Alerts:** Proactive issue detection and notification
|
719
|
+
- **Performance Tracking:** SLA monitoring and reporting
|
720
|
+
- **Capacity Planning:** Usage trends and scaling recommendations
|
721
|
+
|
722
|
+
### Disaster Recovery
|
723
|
+
- **Data Backup:** Automated backups with point-in-time recovery
|
724
|
+
- **Failover Procedures:** Automated service failover and recovery
|
725
|
+
- **Business Continuity:** Critical functions maintained during outages
|
726
|
+
- **Recovery Testing:** Regular DR testing and validation
|
727
|
+
|
728
|
+
## Next Steps
|
729
|
+
|
730
|
+
### Immediate (Next 30 Days)
|
731
|
+
1. **Performance Optimization:** Fine-tune API response times
|
732
|
+
2. **Additional Monitoring:** Enhanced alerting and dashboards
|
733
|
+
3. **Documentation:** Complete integration documentation
|
734
|
+
4. **Team Training:** Operational procedures and troubleshooting
|
735
|
+
|
736
|
+
### Medium-term (Next 90 Days)
|
737
|
+
1. **Additional Integrations:** Social media APIs and customer support
|
738
|
+
2. **Advanced Analytics:** Machine learning and predictive insights
|
739
|
+
3. **Mobile Integration:** Native mobile app API connections
|
740
|
+
4. **International Expansion:** Multi-currency and localization support
|
741
|
+
|
742
|
+
### Long-term (6+ Months)
|
743
|
+
1. **AI Enhancement:** Intelligent automation and decision-making
|
744
|
+
2. **Ecosystem Expansion:** Partner and vendor integrations
|
745
|
+
3. **Advanced Security:** Zero-trust architecture implementation
|
746
|
+
4. **Platform Evolution:** Next-generation integration platform
|
747
|
+
|
748
|
+
---
|
749
|
+
|
750
|
+
**Integration Team Performance:**
|
751
|
+
- All specialists completed their integrations successfully
|
752
|
+
- Cross-system coordination maintained data consistency
|
753
|
+
- Security and compliance requirements fully met
|
754
|
+
- Scalable architecture supports future growth
|
755
|
+
|
756
|
+
*This comprehensive integration system demonstrates the power of specialized AI agents working together to create seamless, secure, and scalable API integrations that drive business value.*
|
757
|
+
SUMMARY
|
758
|
+
|
759
|
+
File.write("#{integration_dir}/INTEGRATION_SUMMARY.md", integration_summary)
|
760
|
+
puts " ✅ INTEGRATION_SUMMARY.md"
|
761
|
+
|
762
|
+
puts "\n🎉 API INTEGRATION COMPLETED!"
|
763
|
+
puts "="*60
|
764
|
+
puts "📁 Complete integration package saved to: #{integration_dir}/"
|
765
|
+
puts ""
|
766
|
+
puts "🔌 **Integration Summary:**"
|
767
|
+
puts " • #{completed_integrations.length} external services integrated"
|
768
|
+
puts " • CRM, Payment, Email, and Analytics systems connected"
|
769
|
+
puts " • Comprehensive error handling and monitoring implemented"
|
770
|
+
puts " • Security and compliance requirements met"
|
771
|
+
puts ""
|
772
|
+
puts "⚡ **Business Benefits Achieved:**"
|
773
|
+
puts " • 15-20 hours/week manual work eliminated"
|
774
|
+
puts " • 99.2% data accuracy through automation"
|
775
|
+
puts " • 30% faster sales cycles"
|
776
|
+
puts " • 25% improved email campaign effectiveness"
|
777
|
+
puts ""
|
778
|
+
puts "🛡️ **Security & Reliability:**"
|
779
|
+
puts " • OAuth 2.0 and API key authentication"
|
780
|
+
puts " • TLS 1.3 encryption for data in transit"
|
781
|
+
puts " • Automated retry logic and error handling"
|
782
|
+
puts " • Real-time monitoring and alerting"
|
783
|
+
```
|
784
|
+
|
785
|
+
## Key API Integration Features
|
786
|
+
|
787
|
+
### 1. **Multi-Service Orchestration**
|
788
|
+
Coordinate integrations across multiple external services:
|
789
|
+
|
790
|
+
```ruby
|
791
|
+
crm_specialist # Customer data synchronization
|
792
|
+
payment_specialist # Transaction processing
|
793
|
+
email_specialist # Marketing automation
|
794
|
+
analytics_specialist # Event tracking
|
795
|
+
api_manager # Cross-system coordination
|
796
|
+
```
|
797
|
+
|
798
|
+
### 2. **Robust Error Handling**
|
799
|
+
Comprehensive error handling with retry logic:
|
800
|
+
|
801
|
+
```ruby
|
802
|
+
# Automatic retry with exponential backoff
|
803
|
+
def make_request_with_retry(method, endpoint, data, headers, retries = 3)
|
804
|
+
# Handle rate limiting, network errors, service outages
|
805
|
+
# Exponential backoff strategy
|
806
|
+
# Circuit breaker patterns
|
807
|
+
end
|
808
|
+
```
|
809
|
+
|
810
|
+
### 3. **Security-First Design**
|
811
|
+
Multiple authentication methods and security controls:
|
812
|
+
|
813
|
+
```ruby
|
814
|
+
# Support for various auth methods
|
815
|
+
auth_type: :bearer # Bearer tokens
|
816
|
+
auth_type: :basic # Basic authentication
|
817
|
+
auth_type: :header # Custom header authentication
|
818
|
+
```
|
819
|
+
|
820
|
+
### 4. **Real-time Monitoring**
|
821
|
+
Comprehensive monitoring and health dashboards:
|
822
|
+
|
823
|
+
- API response time tracking
|
824
|
+
- Error rate monitoring
|
825
|
+
- Data quality metrics
|
826
|
+
- Service health status
|
827
|
+
- Automated alerting
|
828
|
+
|
829
|
+
This API integration system provides a complete framework for connecting RCrewAI crews with external services while maintaining security, reliability, and performance standards.
|