ak0601 commited on
Commit
292aa35
·
verified ·
1 Parent(s): f046ed3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1089
app.py CHANGED
@@ -1,1092 +1,3 @@
1
- # import os
2
- # import re
3
- # import json
4
- # import time
5
- # import asyncio
6
- # from datetime import datetime
7
- # from typing import List, Dict, Any, Optional, Union
8
- # from pydantic import BaseModel, Field, EmailStr, field_validator
9
- # from fastapi import FastAPI, HTTPException, Query, Depends, Request
10
- # from fastapi.responses import JSONResponse, Response
11
- # from fastapi.middleware.cors import CORSMiddleware
12
- # from fastapi.openapi.utils import get_openapi
13
- # import httpx
14
- # from dotenv import load_dotenv
15
-
16
- # # LangChain and OpenAI imports
17
- # try:
18
- # from langchain_openai import ChatOpenAI
19
- # from langchain.prompts import ChatPromptTemplate
20
- # LANGCHAIN_AVAILABLE = True
21
- # except ImportError:
22
- # LANGCHAIN_AVAILABLE = False
23
- # print("Warning: LangChain not available. Install with: pip install langchain langchain-openai")
24
-
25
- # load_dotenv()
26
-
27
- # # Configuration
28
- # SMARTLEAD_API_KEY = os.getenv("SMARTLEAD_API_KEY", "your-api-key-here")
29
- # SMARTLEAD_BASE_URL = "https://server.smartlead.ai/api/v1"
30
-
31
- # # Initialize FastAPI app
32
- # app = FastAPI(
33
- # title="Smartlead API - Complete Integration",
34
- # version="2.1.0",
35
- # description="Comprehensive FastAPI wrapper for Smartlead email automation platform",
36
- # docs_url="/docs",
37
- # redoc_url="/redoc"
38
- # )
39
-
40
- # # Add CORS middleware
41
- # app.add_middleware(
42
- # CORSMiddleware,
43
- # allow_origins=["*"],
44
- # allow_credentials=True,
45
- # allow_methods=["*"],
46
- # allow_headers=["*"],
47
- # )
48
-
49
- # # ============================================================================
50
- # # DATA MODELS
51
- # # ============================================================================
52
-
53
- # class CreateCampaignRequest(BaseModel):
54
- # name: str = Field(..., description="Campaign name")
55
- # client_id: Optional[int] = Field(None, description="Client ID (leave null if no client)")
56
-
57
- # class CampaignScheduleRequest(BaseModel):
58
- # timezone: str = Field(..., description="Timezone for the campaign schedule (e.g., 'America/Los_Angeles')")
59
- # days_of_the_week: List[int] = Field(..., description="Days of the week for scheduling [0=Sunday, 1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday, 6=Saturday]")
60
- # start_hour: str = Field(..., description="Start hour for sending emails in HH:MM format (e.g., '09:00')")
61
- # end_hour: str = Field(..., description="End hour for sending emails in HH:MM format (e.g., '18:00')")
62
- # min_time_btw_emails: int = Field(..., description="Minimum time in minutes between sending emails")
63
- # max_new_leads_per_day: int = Field(..., description="Maximum number of new leads to process per day")
64
- # schedule_start_time: str = Field(..., description="Schedule start time in ISO 8601 format (e.g., '2023-04-25T07:29:25.978Z')")
65
-
66
- # class CampaignSettingsRequest(BaseModel):
67
- # track_settings: List[str] = Field(..., description="Tracking settings array (allowed values: DONT_TRACK_EMAIL_OPEN, DONT_TRACK_LINK_CLICK, DONT_TRACK_REPLY_TO_AN_EMAIL)")
68
- # stop_lead_settings: str = Field(..., description="Settings for stopping leads (allowed values: CLICK_ON_A_LINK, OPEN_AN_EMAIL)")
69
- # unsubscribe_text: str = Field(..., description="Text for the unsubscribe link")
70
- # send_as_plain_text: bool = Field(..., description="Whether emails should be sent as plain text")
71
- # follow_up_percentage: int = Field(ge=0, le=100, description="Follow-up percentage (max 100, min 0)")
72
- # client_id: Optional[int] = Field(None, description="Client ID (leave as null if not needed)")
73
- # enable_ai_esp_matching: bool = Field(False, description="Enable AI ESP matching (by default is false)")
74
-
75
- # class LeadInput(BaseModel):
76
- # first_name: Optional[str] = Field(None, description="Lead's first name")
77
- # last_name: Optional[str] = Field(None, description="Lead's last name")
78
- # email: str = Field(..., description="Lead's email address")
79
- # phone_number: Optional[Union[str, int]] = Field(None, description="Lead's phone number (can be string or integer)")
80
- # company_name: Optional[str] = Field(None, description="Lead's company name")
81
- # website: Optional[str] = Field(None, description="Lead's website")
82
- # location: Optional[str] = Field(None, description="Lead's location")
83
- # custom_fields: Optional[Dict[str, str]] = Field(None, description="Custom fields as key-value pairs (max 20 fields)")
84
- # linkedin_profile: Optional[str] = Field(None, description="Lead's LinkedIn profile URL")
85
- # company_url: Optional[str] = Field(None, description="Company website URL")
86
-
87
- # @field_validator('custom_fields')
88
- # @classmethod
89
- # def validate_custom_fields(cls, v):
90
- # if v is not None and len(v) > 20:
91
- # raise ValueError('Custom fields cannot exceed 20 fields')
92
- # return v
93
-
94
- # @field_validator('phone_number')
95
- # @classmethod
96
- # def validate_phone_number(cls, v):
97
- # if v is not None:
98
- # return str(v)
99
- # return v
100
-
101
- # class LeadSettings(BaseModel):
102
- # ignore_global_block_list: bool = Field(True, description="Ignore leads if they are in the global block list")
103
- # ignore_unsubscribe_list: bool = Field(True, description="Ignore leads if they are in the unsubscribe list")
104
- # ignore_duplicate_leads_in_other_campaign: bool = Field(False, description="Allow leads to be added even if they are duplicates in other campaigns")
105
-
106
- # class AddLeadsRequest(BaseModel):
107
- # lead_list: List[LeadInput] = Field(..., max_items=100, description="List of leads to add (maximum 100 leads)")
108
- # settings: Optional[LeadSettings] = Field(None, description="Settings for lead processing")
109
-
110
- # class AddLeadsResponse(BaseModel):
111
- # ok: bool = Field(..., description="Indicates if the operation was successful")
112
- # upload_count: int = Field(..., description="Number of leads successfully uploaded")
113
- # total_leads: int = Field(..., description="Total number of leads attempted to upload")
114
- # already_added_to_campaign: int = Field(..., description="Number of leads already present in the campaign")
115
- # duplicate_count: int = Field(..., description="Number of duplicate emails found")
116
- # invalid_email_count: int = Field(..., description="Number of leads with invalid email format")
117
- # unsubscribed_leads: Any = Field(..., description="Number of leads that had previously unsubscribed (can be int or empty list)")
118
-
119
- # class SeqDelayDetails(BaseModel):
120
- # delay_in_days: int = Field(..., description="Delay in days before sending this sequence")
121
-
122
- # class SeqVariant(BaseModel):
123
- # subject: str = Field(..., description="Email subject line")
124
- # email_body: str = Field(..., description="Email body content (HTML format)")
125
- # variant_label: str = Field(..., description="Variant label (A, B, C, etc.)")
126
- # id: Optional[int] = Field(None, description="Variant ID (only for updating, not for creating)")
127
-
128
- # class CampaignSequence(BaseModel):
129
- # id: Optional[int] = Field(None, description="Sequence ID (only for updating, not for creating)")
130
- # seq_number: int = Field(..., description="Sequence number (1, 2, 3, etc.)")
131
- # seq_delay_details: SeqDelayDetails = Field(..., description="Delay details for this sequence")
132
- # seq_variants: Optional[List[SeqVariant]] = Field(None, description="Email variants for A/B testing")
133
- # subject: Optional[str] = Field("", description="Subject line (blank for follow-up in same thread)")
134
- # email_body: Optional[str] = Field(None, description="Email body content (HTML format)")
135
-
136
- # class SaveSequencesRequest(BaseModel):
137
- # sequences: List[CampaignSequence] = Field(..., description="List of campaign sequences")
138
-
139
- # class GenerateSequencesRequest(BaseModel):
140
- # job_description: str = Field(..., description="Job description to generate sequences for")
141
-
142
- # class Campaign(BaseModel):
143
- # id: int
144
- # user_id: int
145
- # created_at: datetime
146
- # updated_at: datetime
147
- # status: str
148
- # name: str
149
- # track_settings: Union[str, List[Any]]
150
- # scheduler_cron_value: Optional[Union[str, Dict[str, Any]]] = None
151
- # min_time_btwn_emails: int
152
- # max_leads_per_day: int
153
- # stop_lead_settings: str
154
- # unsubscribe_text: Optional[str] = None
155
- # client_id: Optional[int] = None
156
- # enable_ai_esp_matching: bool
157
- # send_as_plain_text: bool
158
- # follow_up_percentage: Optional[Union[str, int]] = None
159
-
160
- # class CampaignListResponse(BaseModel):
161
- # campaigns: List[Campaign]
162
- # total: int
163
- # source: str
164
-
165
- # class Lead(BaseModel):
166
- # id: int
167
- # email: EmailStr
168
- # first_name: Optional[str] = None
169
- # last_name: Optional[str] = None
170
- # company: Optional[str] = None
171
- # position: Optional[str] = None
172
- # phone_number: Optional[str] = None
173
- # linkedin_url: Optional[str] = None
174
- # status: Optional[str] = None
175
-
176
- # class WarmupDetails(BaseModel):
177
- # status: str
178
- # total_sent_count: int
179
- # total_spam_count: int
180
- # warmup_reputation: str
181
- # warmup_key_id: Optional[str] = None
182
- # warmup_created_at: Optional[datetime] = None
183
- # reply_rate: int
184
- # blocked_reason: Optional[str] = None
185
-
186
- # class EmailAccount(BaseModel):
187
- # id: int
188
- # created_at: datetime
189
- # updated_at: datetime
190
- # user_id: int
191
- # from_name: str
192
- # from_email: str
193
- # username: str
194
- # password: Optional[str] = None
195
- # smtp_host: Optional[str] = None
196
- # smtp_port: Optional[int] = None
197
- # smtp_port_type: Optional[str] = None
198
- # message_per_day: int
199
- # different_reply_to_address: Optional[str] = None
200
- # is_different_imap_account: bool
201
- # imap_username: Optional[str] = None
202
- # imap_password: Optional[str] = None
203
- # imap_host: Optional[str] = None
204
- # imap_port: Optional[int] = None
205
- # imap_port_type: Optional[str] = None
206
- # signature: Optional[str] = None
207
- # custom_tracking_domain: Optional[str] = None
208
- # bcc_email: Optional[str] = None
209
- # is_smtp_success: bool
210
- # is_imap_success: bool
211
- # smtp_failure_error: Optional[str] = None
212
- # imap_failure_error: Optional[str] = None
213
- # type: str
214
- # daily_sent_count: int
215
- # client_id: Optional[int] = None
216
- # campaign_count: Optional[int] = None
217
- # warmup_details: Optional[WarmupDetails] = None
218
-
219
- # class LeadCategoryUpdateRequest(BaseModel):
220
- # category_id: int = Field(..., description="Category ID to assign to the lead")
221
- # pause_lead: bool = Field(False, description="Whether to pause the lead after category update")
222
-
223
- # class CampaignStatusUpdateRequest(BaseModel):
224
- # status: str = Field(..., description="New campaign status (PAUSED, STOPPED, START)")
225
-
226
- # class ResumeLeadRequest(BaseModel):
227
- # resume_lead_with_delay_days: Optional[int] = Field(None, description="Delay in days before resuming (defaults to 0)")
228
-
229
- # class DomainBlockListRequest(BaseModel):
230
- # domain_block_list: List[str] = Field(..., description="List of domains/emails to block")
231
- # client_id: Optional[int] = Field(None, description="Client ID if blocking is client-specific")
232
-
233
- # class WebhookRequest(BaseModel):
234
- # id: Optional[int] = Field(None, description="Webhook ID (null for creating new)")
235
- # name: str = Field(..., description="Webhook name")
236
- # webhook_url: str = Field(..., description="Webhook URL")
237
- # event_types: List[str] = Field(..., description="List of event types to listen for")
238
- # categories: Optional[List[str]] = Field(None, description="List of categories to filter by")
239
-
240
- # class WebhookDeleteRequest(BaseModel):
241
- # id: int = Field(..., description="Webhook ID to delete")
242
-
243
- # class ClientRequest(BaseModel):
244
- # name: str = Field(..., description="Client name")
245
- # email: str = Field(..., description="Client email")
246
- # permission: List[str] = Field(..., description="List of permissions")
247
- # logo: Optional[str] = Field(None, description="Client logo text")
248
- # logo_url: Optional[str] = Field(None, description="Client logo URL")
249
- # password: str = Field(..., description="Client password")
250
-
251
- # class MessageHistoryRequest(BaseModel):
252
- # email_stats_id: str = Field(..., description="Email stats ID for the specific email")
253
- # email_body: str = Field(..., description="Reply message email body")
254
- # reply_message_id: str = Field(..., description="Message ID to reply to")
255
- # reply_email_time: str = Field(..., description="Time of the message being replied to")
256
- # reply_email_body: str = Field(..., description="Body of the message being replied to")
257
- # cc: Optional[str] = Field(None, description="CC recipients")
258
- # bcc: Optional[str] = Field(None, description="BCC recipients")
259
- # add_signature: bool = Field(True, description="Whether to add signature")
260
-
261
- # class AddLeadsAndSequencesRequest(BaseModel):
262
- # lead_list: List[LeadInput] = Field(..., max_items=100, description="List of leads to add (maximum 100 leads)")
263
- # settings: Optional[LeadSettings] = Field(None, description="Settings for lead processing")
264
- # job_description: str = Field(..., description="Job description to generate sequences for")
265
-
266
- # # ============================================================================
267
- # # HELPER FUNCTIONS
268
- # # ============================================================================
269
-
270
- # def _get_smartlead_url(endpoint: str) -> str:
271
- # return f"{SMARTLEAD_BASE_URL}/{endpoint.lstrip('/')}"
272
-
273
- # async def call_smartlead_api(method: str, endpoint: str, data: Any = None, params: Dict[str, Any] = None) -> Any:
274
- # if SMARTLEAD_API_KEY == "your-api-key-here":
275
- # raise HTTPException(status_code=400, detail="Smartlead API key not configured")
276
- # if params is None:
277
- # params = {}
278
- # params['api_key'] = SMARTLEAD_API_KEY
279
- # url = _get_smartlead_url(endpoint)
280
-
281
- # try:
282
- # async with httpx.AsyncClient(timeout=30.0) as client:
283
- # if method.upper() in ("GET", "DELETE"):
284
- # resp = await client.request(method, url, params=params)
285
- # else:
286
- # resp = await client.request(method, url, params=params, json=data)
287
-
288
- # if resp.status_code >= 400:
289
- # try:
290
- # error_data = resp.json()
291
- # error_message = error_data.get('message', error_data.get('error', 'Unknown error'))
292
- # raise HTTPException(status_code=resp.status_code, detail=error_message)
293
- # except (ValueError, KeyError):
294
- # raise HTTPException(status_code=resp.status_code, detail=resp.text)
295
-
296
- # return resp.json()
297
-
298
- # except httpx.TimeoutException:
299
- # raise HTTPException(status_code=408, detail="Request to Smartlead API timed out")
300
- # except httpx.RequestError as e:
301
- # raise HTTPException(status_code=503, detail=f"Failed to connect to Smartlead API: {str(e)}")
302
-
303
- # # ============================================================================
304
- # # CAMPAIGN ENDPOINTS
305
- # # ============================================================================
306
-
307
- # @app.post("/campaigns/create", response_model=Dict[str, Any], tags=["Campaigns"])
308
- # async def create_campaign(campaign: CreateCampaignRequest):
309
- # """Create a new campaign in Smartlead"""
310
- # return await call_smartlead_api("POST", "campaigns/create", data=campaign.dict())
311
-
312
- # @app.get("/campaigns", response_model=CampaignListResponse, tags=["Campaigns"])
313
- # async def list_campaigns():
314
- # """Fetch all campaigns from Smartlead API"""
315
- # campaigns = await call_smartlead_api("GET", "campaigns")
316
- # return {"campaigns": campaigns, "total": len(campaigns), "source": "smartlead"}
317
-
318
- # @app.get("/campaigns/{campaign_id}", response_model=Campaign, tags=["Campaigns"])
319
- # async def get_campaign(campaign_id: int):
320
- # """Get Campaign By Id"""
321
- # return await call_smartlead_api("GET", f"campaigns/{campaign_id}")
322
-
323
- # @app.post("/campaigns/{campaign_id}/settings", response_model=Dict[str, Any], tags=["Campaigns"])
324
- # async def update_campaign_settings(campaign_id: int, settings: CampaignSettingsRequest):
325
- # """Update Campaign General Settings"""
326
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/settings", data=settings.dict())
327
-
328
- # @app.post("/campaigns/{campaign_id}/schedule", response_model=Dict[str, Any], tags=["Campaigns"])
329
- # async def schedule_campaign(campaign_id: int, schedule: CampaignScheduleRequest):
330
- # """Update Campaign Schedule"""
331
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/schedule", data=schedule.dict())
332
-
333
- # @app.delete("/campaigns/{campaign_id}", response_model=Dict[str, Any], tags=["Campaigns"])
334
- # async def delete_campaign(campaign_id: int):
335
- # """Delete Campaign"""
336
- # return await call_smartlead_api("DELETE", f"campaigns/{campaign_id}")
337
-
338
- # @app.post("/campaigns/{campaign_id}/status", response_model=Dict[str, Any], tags=["Campaigns"])
339
- # async def patch_campaign_status(campaign_id: int, request: CampaignStatusUpdateRequest):
340
- # """Patch campaign status"""
341
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/status", data=request.dict())
342
-
343
- # @app.get("/campaigns/{campaign_id}/analytics", response_model=Any, tags=["Analytics"])
344
- # async def campaign_analytics(campaign_id: int):
345
- # """Fetch analytics for a campaign"""
346
- # return await call_smartlead_api("GET", f"campaigns/{campaign_id}/analytics")
347
-
348
- # @app.get("/campaigns/{campaign_id}/statistics", response_model=Dict[str, Any], tags=["Analytics"])
349
- # async def fetch_campaign_statistics_by_campaign_id(
350
- # campaign_id: int,
351
- # offset: int = 0,
352
- # limit: int = 100,
353
- # email_sequence_number: Optional[int] = None,
354
- # email_status: Optional[str] = None
355
- # ):
356
- # """Fetch Campaign Statistics By Campaign Id"""
357
- # params = {"offset": offset, "limit": limit}
358
- # if email_sequence_number:
359
- # params["email_sequence_number"] = email_sequence_number
360
- # if email_status:
361
- # params["email_status"] = email_status
362
- # return await call_smartlead_api("GET", f"campaigns/{campaign_id}/statistics", params=params)
363
-
364
- # @app.get("/campaigns/{campaign_id}/analytics-by-date", response_model=Dict[str, Any], tags=["Analytics"])
365
- # async def fetch_campaign_statistics_by_date_range(
366
- # campaign_id: int,
367
- # start_date: str,
368
- # end_date: str
369
- # ):
370
- # """Fetch Campaign Statistics By Campaign Id And Date Range"""
371
- # params = {"start_date": start_date, "end_date": end_date}
372
- # return await call_smartlead_api("GET", f"campaigns/{campaign_id}/analytics-by-date", params=params)
373
-
374
- # # ============================================================================
375
- # # LEAD MANAGEMENT ENDPOINTS
376
- # # ============================================================================
377
-
378
- # @app.get("/campaigns/{campaign_id}/leads", response_model=Dict[str, Any], tags=["Leads"])
379
- # async def get_campaign_leads(campaign_id: int, offset: int = 0, limit: int = 100):
380
- # """List all leads by campaign id"""
381
- # params = {"offset": offset, "limit": limit}
382
- # return await call_smartlead_api("GET", f"campaigns/{campaign_id}/leads", params=params)
383
-
384
- # # *** MODIFIED: add_leads_to_campaign now uses asyncio.gather for performance ***
385
- # @app.post("/campaigns/{campaign_id}/leads", response_model=Dict[str, Any], tags=["Leads"])
386
- # async def add_leads_to_campaign(campaign_id: int, request: AddLeadsRequest):
387
- # """Add leads to a campaign by ID with personalized welcome and closing messages"""
388
-
389
- # async def process_lead(lead: Dict[str, Any]) -> Dict[str, Any]:
390
- # """Inner function to process a single lead."""
391
- # lead_cleaned = {k: v for k, v in lead.items() if v is not None and v != ""}
392
-
393
- # try:
394
- # personalized_messages = await generate_welcome_closing_messages(lead_cleaned)
395
- # if "custom_fields" not in lead_cleaned:
396
- # lead_cleaned["custom_fields"] = {}
397
- # lead_cleaned["custom_fields"]["Welcome_Message"] = personalized_messages.get("welcome_message", "")
398
- # lead_cleaned["custom_fields"]["Closing_Message"] = personalized_messages.get("closing_message", "")
399
- # except Exception as e:
400
- # print(f"Error generating AI messages for {lead.get('email')}: {e}. Falling back to template.")
401
- # template_messages = generate_template_welcome_closing_messages(lead_cleaned)
402
- # if "custom_fields" not in lead_cleaned:
403
- # lead_cleaned["custom_fields"] = {}
404
- # lead_cleaned["custom_fields"]["Welcome_Message"] = template_messages["welcome_message"]
405
- # lead_cleaned["custom_fields"]["Closing_Message"] = template_messages["closing_message"]
406
-
407
- # return lead_cleaned
408
-
409
- # # Create a list of concurrent tasks for AI processing
410
- # tasks = [process_lead(lead.dict()) for lead in request.lead_list]
411
- # processed_leads = await asyncio.gather(*tasks)
412
-
413
- # # Prepare the final request data for Smartlead
414
- # request_data = {
415
- # "lead_list": processed_leads,
416
- # "settings": request.settings.dict() if request.settings else LeadSettings().dict()
417
- # }
418
-
419
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/leads", data=request_data)
420
-
421
- # @app.post("/campaigns/{campaign_id}/leads/bulk", response_model=Dict[str, Any], tags=["Leads"])
422
- # async def add_bulk_leads(campaign_id: int, leads: List[LeadInput]):
423
- # """Add multiple leads to a Smartlead campaign with personalized messages (legacy endpoint)"""
424
- # request = AddLeadsRequest(lead_list=leads)
425
- # return await add_leads_to_campaign(campaign_id, request)
426
-
427
- # @app.post("/campaigns/{campaign_id}/leads-and-sequences", response_model=Dict[str, Any], tags=["Leads"])
428
- # async def add_leads_and_generate_sequences(campaign_id: int, request: AddLeadsAndSequencesRequest):
429
- # """Add leads to campaign and immediately generate informed sequences using their data"""
430
-
431
- # # Step 1: Add leads with personalized messages
432
- # leads_request = AddLeadsRequest(lead_list=request.lead_list, settings=request.settings)
433
- # leads_result = await add_leads_to_campaign(campaign_id, leads_request)
434
-
435
- # # Step 2: Generate informed sequences using the newly added leads
436
- # try:
437
- # generated_sequences = await generate_sequences_with_llm(request.job_description, campaign_id)
438
- # save_request = SaveSequencesRequest(sequences=generated_sequences)
439
- # sequences_result = await call_smartlead_api("POST", f"campaigns/{campaign_id}/sequences", data=save_request.dict())
440
-
441
- # except Exception as e:
442
- # print(f"Error generating sequences after adding leads: {str(e)}")
443
- # # Fallback to generic sequences
444
- # generated_sequences = await generate_sequences_with_llm(request.job_description)
445
- # save_request = SaveSequencesRequest(sequences=generated_sequences)
446
- # sequences_result = await call_smartlead_api("POST", f"campaigns/{campaign_id}/sequences", data=save_request.dict())
447
-
448
- # return {
449
- # "ok": True,
450
- # "message": "Leads added and informed sequences generated successfully",
451
- # "leads_result": leads_result,
452
- # "sequences_result": sequences_result,
453
- # "generated_sequences": [seq.dict() for seq in generated_sequences]
454
- # }
455
-
456
- # @app.post("/campaigns/{campaign_id}/leads/{lead_id}/resume", response_model=Dict[str, Any], tags=["Leads"])
457
- # async def resume_lead_by_campaign_id(campaign_id: int, lead_id: int, request: ResumeLeadRequest):
458
- # """Resume Lead By Campaign ID"""
459
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/leads/{lead_id}/resume", data=request.dict())
460
-
461
- # @app.post("/campaigns/{campaign_id}/leads/{lead_id}/pause", response_model=Dict[str, Any], tags=["Leads"])
462
- # async def pause_lead_by_campaign_id(campaign_id: int, lead_id: int):
463
- # """Pause Lead By Campaign ID"""
464
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/leads/{lead_id}/pause")
465
-
466
- # @app.delete("/campaigns/{campaign_id}/leads/{lead_id}", response_model=Dict[str, Any], tags=["Leads"])
467
- # async def delete_lead_by_campaign_id(campaign_id: int, lead_id: int):
468
- # """Delete Lead By Campaign ID"""
469
- # return await call_smartlead_api("DELETE", f"campaigns/{campaign_id}/leads/{lead_id}")
470
-
471
- # @app.post("/campaigns/{campaign_id}/leads/{lead_id}/unsubscribe", response_model=Dict[str, Any], tags=["Leads"])
472
- # async def unsubscribe_lead_from_campaign(campaign_id: int, lead_id: int):
473
- # """Unsubscribe/Pause Lead From Campaign"""
474
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/leads/{lead_id}/unsubscribe")
475
-
476
- # @app.post("/leads/{lead_id}/unsubscribe", response_model=Dict[str, Any], tags=["Leads"])
477
- # async def unsubscribe_lead_from_all_campaigns(lead_id: int):
478
- # """Unsubscribe Lead From All Campaigns"""
479
- # return await call_smartlead_api("POST", f"leads/{lead_id}/unsubscribe")
480
-
481
- # @app.post("/leads/{lead_id}", response_model=Dict[str, Any], tags=["Leads"])
482
- # async def update_lead(lead_id: int, lead_data: Dict[str, Any]):
483
- # """Update lead using the Lead ID"""
484
- # return await call_smartlead_api("POST", f"leads/{lead_id}", data=lead_data)
485
-
486
- # @app.post("/campaigns/{campaign_id}/leads/{lead_id}/category", response_model=Dict[str, Any], tags=["Leads"])
487
- # async def update_lead_category_by_campaign(campaign_id: int, lead_id: int, request: LeadCategoryUpdateRequest):
488
- # """Update a lead's category based on their campaign"""
489
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/leads/{lead_id}/category", data=request.dict())
490
-
491
- # @app.post("/leads/add-domain-block-list", response_model=Dict[str, Any], tags=["Leads"])
492
- # async def add_domain_to_global_block_list(request: DomainBlockListRequest):
493
- # """Add Lead/Domain to Global Block List"""
494
- # return await call_smartlead_api("POST", "leads/add-domain-block-list", data=request.dict())
495
-
496
- # @app.get("/leads/fetch-categories", response_model=List[Dict[str, Any]], tags=["Leads"])
497
- # async def fetch_lead_categories():
498
- # """Fetch lead categories"""
499
- # return await call_smartlead_api("GET", "leads/fetch-categories")
500
-
501
- # @app.get("/leads", response_model=Dict[str, Any], tags=["Leads"])
502
- # async def fetch_lead_by_email_address(email: str):
503
- # """Fetch lead by email address"""
504
- # return await call_smartlead_api("GET", "leads", params={"email": email})
505
-
506
- # @app.get("/leads/{lead_id}/campaigns", response_model=List[Dict[str, Any]], tags=["Leads"])
507
- # async def campaigns_for_lead(lead_id: int):
508
- # """Fetch all campaigns that a lead belongs to"""
509
- # return await call_smartlead_api("GET", f"leads/{lead_id}/campaigns")
510
-
511
- # @app.get("/campaigns/{campaign_id}/leads/check", response_model=Dict[str, Any], tags=["Leads"])
512
- # async def check_lead_in_campaign(campaign_id: int, email: str):
513
- # """Check if a lead exists in a campaign using efficient indexed lookups"""
514
- # try:
515
- # lead_response = await call_smartlead_api("GET", "leads", params={"email": email})
516
-
517
- # if not lead_response or "id" not in lead_response:
518
- # return {"exists": False, "message": "Lead not found"}
519
-
520
- # lead_id = lead_response["id"]
521
- # campaigns_response = await call_smartlead_api("GET", f"leads/{lead_id}/campaigns")
522
-
523
- # if not campaigns_response:
524
- # return {"exists": False, "message": "No campaigns found for lead"}
525
-
526
- # campaign_exists = any(campaign.get("id") == campaign_id for campaign in campaigns_response)
527
-
528
- # return {"exists": campaign_exists, "message": "Lead found in campaign" if campaign_exists else "Lead not found in campaign"}
529
-
530
- # except HTTPException as e:
531
- # if e.status_code == 404:
532
- # return {"exists": False, "message": "Lead not found"}
533
- # raise e
534
- # except Exception as e:
535
- # raise HTTPException(status_code=500, detail=f"Error checking lead in campaign: {str(e)}")
536
-
537
- # @app.get("/campaigns/{campaign_id}/leads-export", tags=["Leads"])
538
- # async def export_data_from_campaign(campaign_id: int):
539
- # """Export data from a campaign as CSV"""
540
- # if SMARTLEAD_API_KEY == "your-api-key-here":
541
- # raise HTTPException(status_code=400, detail="Smartlead API key not configured")
542
-
543
- # url = _get_smartlead_url(f"campaigns/{campaign_id}/leads-export")
544
- # params = {"api_key": SMARTLEAD_API_KEY}
545
-
546
- # try:
547
- # async with httpx.AsyncClient(timeout=30.0) as client:
548
- # resp = await client.get(url, params=params)
549
-
550
- # if resp.status_code >= 400:
551
- # try:
552
- # error_data = resp.json()
553
- # error_message = error_data.get('message', error_data.get('error', 'Unknown error'))
554
- # raise HTTPException(status_code=resp.status_code, detail=error_message)
555
- # except (ValueError, KeyError):
556
- # raise HTTPException(status_code=resp.status_code, detail=resp.text)
557
-
558
- # return Response(
559
- # content=resp.text,
560
- # media_type="text/csv",
561
- # headers={"Content-Disposition": f"attachment; filename=campaign_{campaign_id}_leads.csv"}
562
- # )
563
-
564
- # except httpx.TimeoutException:
565
- # raise HTTPException(status_code=408, detail="Request to Smartlead API timed out")
566
- # except httpx.RequestError as e:
567
- # raise HTTPException(status_code=503, detail=f"Failed to connect to Smartlead API: {str(e)}")
568
-
569
- # # ============================================================================
570
- # # SEQUENCE ENDPOINTS
571
- # # ============================================================================
572
-
573
- # @app.get("/campaigns/{campaign_id}/sequences", response_model=Any, tags=["Sequences"])
574
- # async def get_campaign_sequences(campaign_id: int):
575
- # """Fetch email sequences for a campaign"""
576
- # return await call_smartlead_api("GET", f"campaigns/{campaign_id}/sequences")
577
-
578
- # @app.post("/campaigns/{campaign_id}/sequences", response_model=Dict[str, Any], tags=["Sequences"])
579
- # async def save_campaign_sequences(campaign_id: int, request: SaveSequencesRequest):
580
- # """Save Campaign Sequence"""
581
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/sequences", data=request.dict())
582
-
583
- # # *** MODIFIED: generate_campaign_sequences now uses the corrected AI function ***
584
- # @app.post("/campaigns/{campaign_id}/sequences/generate", response_model=Dict[str, Any], tags=["Sequences"])
585
- # async def generate_campaign_sequences(campaign_id: int, request: GenerateSequencesRequest):
586
- # """Generate a campaign sequence template using AI that leverages personalized custom fields."""
587
- # job_description = request.job_description
588
-
589
- # # Generate the smart template
590
- # generated_sequences = await generate_sequences_with_llm(job_description, campaign_id)
591
-
592
- # # Save the template to the campaign
593
- # save_request = SaveSequencesRequest(sequences=generated_sequences)
594
- # result = await call_smartlead_api("POST", f"campaigns/{campaign_id}/sequences", data=save_request.dict())
595
-
596
- # return {
597
- # "ok": True,
598
- # "message": "Sequence template generated and saved successfully. It will use personalized fields for each lead.",
599
- # "generated_sequences": [seq.dict() for seq in generated_sequences],
600
- # "save_result": result
601
- # }
602
-
603
- # # ============================================================================
604
- # # WEBHOOK ENDPOINTS
605
- # # ============================================================================
606
-
607
- # @app.get("/campaigns/{campaign_id}/webhooks", response_model=List[Dict[str, Any]], tags=["Webhooks"])
608
- # async def fetch_webhooks_by_campaign_id(campaign_id: int):
609
- # """Fetch Webhooks By Campaign ID"""
610
- # return await call_smartlead_api("GET", f"campaigns/{campaign_id}/webhooks")
611
-
612
- # @app.post("/campaigns/{campaign_id}/webhooks", response_model=Dict[str, Any], tags=["Webhooks"])
613
- # async def add_update_campaign_webhook(campaign_id: int, request: WebhookRequest):
614
- # """Add / Update Campaign Webhook"""
615
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/webhooks", data=request.dict())
616
-
617
- # @app.delete("/campaigns/{campaign_id}/webhooks", response_model=Dict[str, Any], tags=["Webhooks"])
618
- # async def delete_campaign_webhook(campaign_id: int, request: WebhookDeleteRequest):
619
- # """Delete Campaign Webhook"""
620
- # return await call_smartlead_api("DELETE", f"campaigns/{campaign_id}/webhooks", data=request.dict())
621
-
622
- # # ============================================================================
623
- # # CLIENT MANAGEMENT ENDPOINTS
624
- # # ============================================================================
625
-
626
- # @app.post("/client/save", response_model=Dict[str, Any], tags=["Clients"])
627
- # async def add_client_to_system(request: ClientRequest):
628
- # """Add Client To System (Whitelabel or not)"""
629
- # return await call_smartlead_api("POST", "client/save", data=request.dict())
630
-
631
- # @app.get("/client", response_model=List[Dict[str, Any]], tags=["Clients"])
632
- # async def fetch_all_clients():
633
- # """Fetch all clients"""
634
- # return await call_smartlead_api("GET", "client")
635
-
636
- # # ============================================================================
637
- # # MESSAGE HISTORY AND REPLY ENDPOINTS
638
- # # ============================================================================
639
-
640
- # @app.get("/campaigns/{campaign_id}/leads/{lead_id}/message-history", response_model=Dict[str, Any], tags=["Messages"])
641
- # async def fetch_lead_message_history_based_on_campaign(campaign_id: int, lead_id: int):
642
- # """Fetch Lead Message History Based On Campaign"""
643
- # return await call_smartlead_api("GET", f"campaigns/{campaign_id}/leads/{lead_id}/message-history")
644
-
645
- # @app.post("/campaigns/{campaign_id}/reply-email-thread", response_model=Dict[str, Any], tags=["Messages"])
646
- # async def reply_to_lead_from_master_inbox(campaign_id: int, request: MessageHistoryRequest):
647
- # """Reply To Lead From Master Inbox via API"""
648
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/reply-email-thread", data=request.dict())
649
-
650
- # # ============================================================================
651
- # # EMAIL ACCOUNT ENDPOINTS
652
- # # ============================================================================
653
-
654
- # @app.get("/email-accounts", response_model=List[EmailAccount], tags=["Email Accounts"])
655
- # async def list_email_accounts(offset: int = 0, limit: int = 100):
656
- # """List all email accounts with optional pagination"""
657
- # params = {"offset": offset, "limit": limit}
658
- # return await call_smartlead_api("GET", "email-accounts", params=params)
659
-
660
- # @app.post("/email-accounts/save", response_model=Any, tags=["Email Accounts"])
661
- # async def save_email_account(account: Dict[str, Any]):
662
- # """Create an Email Account"""
663
- # return await call_smartlead_api("POST", "email-accounts/save", data=account)
664
-
665
- # @app.get("/email-accounts/{account_id}", response_model=EmailAccount, tags=["Email Accounts"])
666
- # async def get_email_account(account_id: int):
667
- # """Fetch Email Account By ID"""
668
- # return await call_smartlead_api("GET", f"email-accounts/{account_id}")
669
-
670
- # @app.post("/email-accounts/{account_id}", response_model=Any, tags=["Email Accounts"])
671
- # async def update_email_account(account_id: int, payload: Dict[str, Any]):
672
- # """Update Email Account"""
673
- # return await call_smartlead_api("POST", f"email-accounts/{account_id}", data=payload)
674
-
675
- # @app.post("/email-accounts/{account_id}/warmup", response_model=Any, tags=["Email Accounts"])
676
- # async def set_warmup(account_id: int, payload: Dict[str, Any]):
677
- # """Add/Update Warmup To Email Account"""
678
- # return await call_smartlead_api("POST", f"email-accounts/{account_id}/warmup", data=payload)
679
-
680
- # @app.get("/email-accounts/{account_id}/warmup-stats", response_model=Any, tags=["Email Accounts"])
681
- # async def get_warmup_stats(account_id: int):
682
- # """Fetch Warmup Stats By Email Account ID"""
683
- # return await call_smartlead_api("GET", f"email-accounts/{account_id}/warmup-stats")
684
-
685
- # @app.get("/campaigns/{campaign_id}/email-accounts", response_model=List[EmailAccount], tags=["Email Accounts"])
686
- # async def list_campaign_email_accounts(campaign_id: int):
687
- # """List all email accounts per campaign"""
688
- # return await call_smartlead_api("GET", f"campaigns/{campaign_id}/email-accounts")
689
-
690
- # @app.post("/campaigns/{campaign_id}/email-accounts", response_model=Any, tags=["Email Accounts"])
691
- # async def add_campaign_email_accounts(campaign_id: int, payload: Dict[str, Any]):
692
- # """Add Email Account To A Campaign"""
693
- # return await call_smartlead_api("POST", f"campaigns/{campaign_id}/email-accounts", data=payload)
694
-
695
- # @app.delete("/campaigns/{campaign_id}/email-accounts", response_model=Any, tags=["Email Accounts"])
696
- # async def remove_campaign_email_accounts(campaign_id: int, payload: Dict[str, Any]):
697
- # """Remove Email Account From A Campaign"""
698
- # return await call_smartlead_api("DELETE", f"campaigns/{campaign_id}/email-accounts", data=payload)
699
-
700
- # @app.post("/email-accounts/reconnect-failed-email-accounts", response_model=Dict[str, Any], tags=["Email Accounts"])
701
- # async def reconnect_failed_email_accounts():
702
- # """Reconnect failed email accounts"""
703
- # return await call_smartlead_api("POST", "email-accounts/reconnect-failed-email-accounts")
704
-
705
- # # ============================================================================
706
- # # UTILITY ENDPOINTS
707
- # # ============================================================================
708
-
709
- # @app.get("/health", response_model=Dict[str, Any], tags=["Utilities"])
710
- # async def health_check():
711
- # """Health check endpoint to verify API connectivity"""
712
- # try:
713
- # campaigns = await call_smartlead_api("GET", "campaigns")
714
- # return {
715
- # "status": "healthy",
716
- # "message": "Smartlead API is accessible",
717
- # "campaigns_count": len(campaigns) if isinstance(campaigns, list) else 0,
718
- # "timestamp": datetime.now().isoformat()
719
- # }
720
- # except Exception as e:
721
- # return {
722
- # "status": "unhealthy",
723
- # "message": f"Smartlead API connection failed: {str(e)}",
724
- # "timestamp": datetime.now().isoformat()
725
- # }
726
-
727
- # @app.get("/api-info", response_model=Dict[str, Any], tags=["Utilities"])
728
- # async def api_info():
729
- # """Get information about the API and available endpoints"""
730
- # return {
731
- # "name": "Smartlead API - Complete Integration",
732
- # "version": "2.0.0",
733
- # "description": "Comprehensive FastAPI wrapper for Smartlead email automation platform",
734
- # "base_url": SMARTLEAD_BASE_URL,
735
- # "available_endpoints": [
736
- # "Campaign Management",
737
- # "Lead Management",
738
- # "Sequence Management",
739
- # "Webhook Management",
740
- # "Client Management",
741
- # "Message History & Reply",
742
- # "Analytics",
743
- # "Email Account Management"
744
- # ],
745
- # "documentation": "Based on Smartlead API documentation",
746
- # "timestamp": datetime.now().isoformat()
747
- # }
748
-
749
- # # ============================================================================
750
- # # AI SEQUENCE GENERATION FUNCTIONS
751
- # # ============================================================================
752
-
753
- # async def generate_welcome_closing_messages(lead_data: Dict[str, Any]) -> Dict[str, str]:
754
- # class structure(BaseModel):
755
- # welcome_message: str = Field(description="Welcome message for the candidate")
756
- # closing_message: str = Field(description="Closing message for the candidate")
757
-
758
- # """Generate personalized welcome and closing messages using LLM based on candidate details"""
759
-
760
- # if not LANGCHAIN_AVAILABLE:
761
- # return generate_template_welcome_closing_messages(lead_data)
762
-
763
- # try:
764
- # openai_api_key = os.getenv("OPENAI_API_KEY")
765
- # if not openai_api_key:
766
- # print("Warning: OPENAI_API_KEY not set. Using template messages.")
767
- # return generate_template_welcome_closing_messages(lead_data)
768
-
769
- # llm = ChatOpenAI(
770
- # model="gpt-4o",
771
- # temperature=0.7,
772
- # openai_api_key=openai_api_key
773
- # )
774
- # str_llm = llm.with_structured_output(structure)
775
-
776
- # first_name = lead_data.get("first_name", "")
777
- # company_name = lead_data.get("company_name", "")
778
- # title = lead_data.get("custom_fields", {}).get("Title", "")
779
-
780
- # candidate_info = f"Name: {first_name}, Company: {company_name}, Title: {title}"
781
-
782
- # system_prompt = """You are an expert recruiter creating personalized messages. Generate a 2-sentence welcome message and a 1-sentence closing message. Be professional and friendly and sound like real human recruitor. Reference their background. Respond with ONLY valid JSON."""
783
-
784
- # prompt_template = ChatPromptTemplate.from_messages([
785
- # ("system", system_prompt),
786
- # ("human", "Generate messages for this candidate: {candidate_info}")
787
- # ])
788
-
789
- # messages = prompt_template.format_messages(candidate_info=candidate_info)
790
- # response = await str_llm.ainvoke(messages)
791
-
792
- # return {
793
- # "welcome_message": response.welcome_message,
794
- # "closing_message": response.closing_message
795
- # }
796
- # except Exception as e:
797
- # print(f"Error generating welcome/closing messages with LLM: {str(e)}")
798
- # return generate_template_welcome_closing_messages(lead_data)
799
-
800
- # def generate_template_welcome_closing_messages(lead_data: Dict[str, Any]) -> Dict[str, str]:
801
- # """Generate template-based welcome and closing messages as fallback"""
802
- # first_name = lead_data.get("first_name", "there")
803
- # welcome_message = f"Hi {first_name}, I came across your profile and was impressed by your background."
804
- # closing_message = f"Looking forward to connecting with you, {first_name}!"
805
- # return {"welcome_message": welcome_message, "closing_message": closing_message}
806
-
807
- # # *** MODIFIED: generate_sequences_with_llm now creates a smart template ***
808
- # async def generate_sequences_with_llm(job_description: str, campaign_id: Optional[int] = None) -> List[CampaignSequence]:
809
- # """Generate an email sequence template using LangChain and OpenAI, optionally informed by campaign lead data."""
810
-
811
- # class EmailContent(BaseModel):
812
- # subject: str = Field(description="Subject line for the email")
813
- # body: str = Field(description="Body of the email, using placeholders")
814
-
815
- # class SequenceStructure(BaseModel):
816
- # introduction: EmailContent
817
- # follow_up_1: EmailContent
818
- # follow_up_2: EmailContent
819
-
820
- # if not LANGCHAIN_AVAILABLE:
821
- # return generate_template_sequences(job_description)
822
-
823
- # try:
824
- # openai_api_key = os.getenv("OPENAI_API_KEY")
825
- # if not openai_api_key:
826
- # print("Warning: OPENAI_API_KEY not set. Using template sequences.")
827
- # return generate_template_sequences(job_description)
828
-
829
- # # If campaign_id is provided, fetch lead data to inform the template
830
- # lead_context = ""
831
- # if campaign_id:
832
- # try:
833
- # leads_response = await call_smartlead_api("GET", f"campaigns/{campaign_id}/leads", params={"limit": 10})
834
- # campaign_leads = leads_response.get("leads", []) if isinstance(leads_response, dict) else leads_response
835
-
836
- # if campaign_leads:
837
- # # Sample lead data to inform template generation
838
- # sample_leads = campaign_leads[:3]
839
- # lead_info = []
840
- # for lead in sample_leads:
841
- # custom_fields = lead.get("custom_fields", {})
842
- # lead_info.append({
843
- # "first_name": lead.get("first_name", ""),
844
- # "company": lead.get("company_name", ""),
845
- # "title": custom_fields.get("Title", ""),
846
- # "welcome_msg": custom_fields.get("Welcome_Message", ""),
847
- # "closing_msg": custom_fields.get("Closing_Message", "")
848
- # })
849
-
850
- # lead_context = f"\n\nCampaign Lead Context (sample of {len(campaign_leads)} leads):\n{json.dumps(lead_info, indent=2)}"
851
-
852
- # except Exception as e:
853
- # print(f"Could not fetch lead data for campaign {campaign_id}: {e}")
854
-
855
- # llm = ChatOpenAI(model="gpt-4o", temperature=0.7, openai_api_key=openai_api_key)
856
- # structured_llm = llm.with_structured_output(SequenceStructure)
857
-
858
- # system_prompt = """You are an expert email sequence template generator for recruitment campaigns on behalf of 'Ali Taghikhani, CEO SRN'.
859
-
860
- # Your task is to generate a 3-step email sequence template for a given job description.
861
- # Email Sequence Structure:
862
- # 1. INTRODUCTION (Day 1): Ask for consent and interest in the role, In the starting use the welcome message placeholder after the salutation, and in the end use closing message template along with the name and title of sender
863
- # 2. OUTREACH (Day 3): Provide detailed job information
864
- # 3. FOLLOW-UP (Day 5): Follow up on updates and next steps
865
- # Requirements:
866
- # - First sequence will only ask about the consent and interest in the role, no other information is needed.
867
- # - Second and third sequences are follow-ups (no subject line needed) in the 3rd sequence try providing some information about the role and the company.
868
- # - All emails should be HTML formatted with proper <br> tags
869
- # - Professional but friendly tone
870
- # - Include clear call-to-actions
871
- # - Focus on building consent and trust
872
-
873
- # **CRITICAL FORMATTING RULES:**
874
- # 1. **PLACEHOLDER FORMAT IS ESSENTIAL:** You MUST use double curly braces for all placeholders.
875
- # - **CORRECT:** `{{first_name}}`
876
- # - **INCORRECT:** `{first_name}` or `[first_name]` or `<first_name>`
877
- # 2. **REQUIRED PLACEHOLDERS:** You MUST include `{{Welcome_Message}}` and `{{Closing_Message}}` in the first email. You should also use `{{first_name}}` in follow-ups.
878
- # 3. **FIRST EMAIL STRUCTURE:** The first email's body MUST begin with `{{Welcome_Message}}` and end with `{{Closing_Message}}`.
879
- # 4. **SIGNATURE:** End EVERY email body with `<br><br>Best regards,<br>Ali Taghikhani<br>CEO, SRN`.
880
- # 5. **EXAMPLE BODY:**
881
- # ```html
882
- # {{Welcome_Message}}<br><br>I saw your profile and was impressed. We have an opening for a Senior Engineer that seems like a great fit.<br><br>{{Closing_Message}}<br><br>Best regards,<br>Ali Taghikhani<br>CEO, SRN>
883
- # ```
884
- # Always try to start the message with the salutation except for the first email.
885
- # If lead context is provided, use it to make the templates more relevant.
886
- # Respond with ONLY a valid JSON object matching the required structure.
887
- # """
888
-
889
- # prompt = ChatPromptTemplate.from_messages([
890
- # ("system", system_prompt),
891
- # ("human", "Generate the 3-step email sequence template for this job description: {job_description}{lead_context}")
892
- # ])
893
-
894
- # # By using .partial, we tell LangChain to treat the Smartlead placeholders as literals
895
- # # and not expect them as input variables. This is the correct way to handle this.
896
- # partial_prompt = prompt.partial(
897
- # first_name="",
898
- # company_name="",
899
- # **{"Welcome_Message": "", "Closing_Message": "", "Title": ""}
900
- # )
901
-
902
- # chain = partial_prompt | structured_llm
903
- # response = await chain.ainvoke({"job_description": job_description, "lead_context": lead_context})
904
-
905
- # # Post-process the AI's response to enforce double curly braces.
906
- # # This is a robust way to fix the AI's tendency to use single braces.
907
- # def fix_braces(text: str) -> str:
908
- # if not text:
909
- # return ""
910
- # # This regex finds all occurrences of `{...}` that are not `{{...}}`
911
- # # and replaces them with `{{...}}`.
912
- # return re.sub(r'{([^{}\n]+)}', r'{{\1}}', text)
913
-
914
- # sequences = [
915
- # CampaignSequence(
916
- # seq_number=1,
917
- # seq_delay_details=SeqDelayDetails(delay_in_days=1),
918
- # seq_variants=[SeqVariant(
919
- # subject=fix_braces(response.introduction.subject),
920
- # email_body=fix_braces(response.introduction.body),
921
- # variant_label="A"
922
- # )]
923
- # ),
924
- # CampaignSequence(
925
- # seq_number=2,
926
- # seq_delay_details=SeqDelayDetails(delay_in_days=3),
927
- # subject="", # Same thread
928
- # email_body=fix_braces(response.follow_up_1.body)
929
- # ),
930
- # CampaignSequence(
931
- # seq_number=3,
932
- # seq_delay_details=SeqDelayDetails(delay_in_days=5),
933
- # subject="", # Same thread
934
- # email_body=fix_braces(response.follow_up_2.body)
935
- # )
936
- # ]
937
- # return sequences
938
-
939
- # except Exception as e:
940
- # print(f"Error generating sequences with LLM: {str(e)}. Falling back to template.")
941
- # return generate_template_sequences(job_description)
942
-
943
- # def generate_template_sequences(job_description: str) -> List[CampaignSequence]:
944
- # """Generate template-based sequences as fallback, using correct placeholders."""
945
-
946
- # # This is the corrected structure for the first email
947
- # first_email_body = f"""<p>{{{{custom.Welcome_Message}}}}<br><br>
948
- # I'm reaching out because we have some exciting opportunities for a {job_description} that might be a great fit for your background. Are you currently open to exploring new roles?<br><br>
949
- # {{{{custom.Closing_Message}}}}<br><br>
950
- # Best regards,<br>Ali Taghikhani<br>CEO, SRN</p>"""
951
-
952
- # follow_up_1_body = f"""<p>Hi {{{{first_name}}}},<br><br>
953
- # Just wanted to follow up on my previous email regarding the {job_description} role. I'd love to hear your thoughts when you have a moment.<br><br>
954
- # Best regards,<br>Ali Taghikhani<br>CEO, SRN</p>"""
955
-
956
- # follow_up_2_body = f"""<p>Hi {{{{first_name}}}},<br><br>
957
- # Checking in one last time about the {job_description} opportunity. If the timing isn't right, no worries at all. Otherwise, I look forward to hearing from you.<br><br>
958
- # Best regards,<br>Ali Taghikhani<br>CEO, SRN</p>"""
959
-
960
- # sequences = [
961
- # CampaignSequence(
962
- # seq_number=1,
963
- # seq_delay_details=SeqDelayDetails(delay_in_days=1),
964
- # seq_variants=[
965
- # SeqVariant(
966
- # subject=f"Regarding a {job_description} opportunity",
967
- # email_body=first_email_body,
968
- # variant_label="A"
969
- # )
970
- # ]
971
- # ),
972
- # CampaignSequence(
973
- # seq_number=2,
974
- # seq_delay_details=SeqDelayDetails(delay_in_days=3),
975
- # subject="",
976
- # email_body=follow_up_1_body
977
- # ),
978
- # CampaignSequence(
979
- # seq_number=3,
980
- # seq_delay_details=SeqDelayDetails(delay_in_days=5),
981
- # subject="",
982
- # email_body=follow_up_2_body
983
- # )
984
- # ]
985
- # return sequences
986
-
987
- # # ============================================================================
988
- # # RATE LIMITING MIDDLEWARE
989
- # # ============================================================================
990
-
991
- # class RateLimiter:
992
- # def __init__(self, max_requests: int = 10, window_seconds: int = 2):
993
- # self.max_requests = max_requests
994
- # self.window_seconds = window_seconds
995
- # self.requests = []
996
-
997
- # def is_allowed(self) -> bool:
998
- # now = time.time()
999
- # self.requests = [req_time for req_time in self.requests if now - req_time < self.window_seconds]
1000
- # if len(self.requests) >= self.max_requests:
1001
- # return False
1002
- # self.requests.append(now)
1003
- # return True
1004
-
1005
- # rate_limiter = RateLimiter(max_requests=10, window_seconds=2)
1006
-
1007
- # @app.middleware("http")
1008
- # async def rate_limit_middleware(request: Request, call_next):
1009
- # """Rate limiting middleware to respect Smartlead's API limits"""
1010
- # if not rate_limiter.is_allowed():
1011
- # return JSONResponse(
1012
- # status_code=429,
1013
- # content={"error": "Rate limit exceeded"}
1014
- # )
1015
- # response = await call_next(request)
1016
- # return response
1017
-
1018
- # # ============================================================================
1019
- # # ERROR HANDLING
1020
- # # ============================================================================
1021
-
1022
- # @app.exception_handler(HTTPException)
1023
- # async def http_exception_handler(request: Request, exc: HTTPException):
1024
- # """Custom HTTP exception handler"""
1025
- # return JSONResponse(
1026
- # status_code=exc.status_code,
1027
- # content={"error": True, "message": exc.detail}
1028
- # )
1029
-
1030
- # @app.exception_handler(Exception)
1031
- # async def general_exception_handler(request: Request, exc: Exception):
1032
- # """General exception handler"""
1033
- # return JSONResponse(
1034
- # status_code=500,
1035
- # content={
1036
- # "error": True,
1037
- # "message": "Internal server error",
1038
- # "detail": str(exc) if os.getenv("DEBUG") else None
1039
- # }
1040
- # )
1041
-
1042
- # # ============================================================================
1043
- # # CUSTOM OPENAPI SCHEMA
1044
- # # ============================================================================
1045
-
1046
- # def custom_openapi():
1047
- # if app.openapi_schema:
1048
- # return app.openapi_schema
1049
-
1050
- # openapi_schema = get_openapi(
1051
- # title="Smartlead API - Complete Integration",
1052
- # version="2.1.0",
1053
- # description="A comprehensive FastAPI wrapper for the Smartlead email automation platform.",
1054
- # routes=app.routes,
1055
- # )
1056
-
1057
- # openapi_schema["tags"] = [
1058
- # {"name": "Campaigns", "description": "Campaign management operations"},
1059
- # {"name": "Leads", "description": "Lead management operations"},
1060
- # {"name": "Sequences", "description": "Email sequence management"},
1061
- # {"name": "Webhooks", "description": "Webhook management"},
1062
- # {"name": "Clients", "description": "Client account management"},
1063
- # {"name": "Messages", "description": "Message history and reply operations"},
1064
- # {"name": "Analytics", "description": "Campaign analytics and statistics"},
1065
- # {"name": "Email Accounts", "description": "Email account management"},
1066
- # {"name": "Utilities", "description": "Utility endpoints"}
1067
- # ]
1068
-
1069
- # app.openapi_schema = openapi_schema
1070
- # return app.openapi_schema
1071
-
1072
- # app.openapi = custom_openapi
1073
-
1074
- # # ============================================================================
1075
- # # MAIN APPLICATION ENTRY POINT
1076
- # # ============================================================================
1077
-
1078
- # if __name__ == "__main__":
1079
- # import uvicorn
1080
-
1081
- # print("Starting Smartlead API - Complete Integration")
1082
- # uvicorn.run(
1083
- # "__main__:app",
1084
- # host="0.0.0.0",
1085
- # port=8000,
1086
- # reload=True,
1087
- # log_level="info"
1088
- # )
1089
-
1090
  import os
1091
  import re
1092
  import json
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import re
3
  import json