Spaces:
Runtime error
Runtime error
Upload utils.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136from openai import OpenAIimport osimport jsonimport refrom datetime import datetimeclient = OpenAI()def generate_rtm(company, website, use_serper=False, workspace="unknown"):prompt = f"""You are an expert enterprise sales strategist specializing in digital operations, automation, and AI-driven solutions. Your task is to craft a compelling, personalized 'Reason to Meet' (RTM) narrative for a prospective client, integrating insights from PagerDuty's latest offerings and aligning them with the client's specific challenges and objectives.Company: {company}Website: {website}Follow this structured format with bold markdown headers and bullet points per section:**1. Company Overview**- HQ, employee size, core offerings, notable brands, public/private, recent growth indicators**2. Business Strategy & Transformation**- Recent M&A, digital transformation, AI/cloud investments, platform modernization- Key business drivers from investor reports or public interviews**3. Operational Challenges**- MTTR, service reliability, NOC costs, alert noise, fragmented toolchains, compliance pressures- Specific operational KPIs, pain points or risk factors**4. Executive Focus**- List key executives (CIO, CTO, COO, CISO, VP Engineering/Infrastructure/Ops)- Include recent public comments or strategic priorities if found**5. PagerDuty-Relevant Opportunities**- Align these pain points to PagerDuty capabilities:- Operations Cloud: full-stack digital operations- Incident Management: intelligent routing, escalation, service ownership- AIOps: noise reduction, event intelligence- Automation: runbook automation, workflow orchestration- Business Operations: customer communications, status pages- Agentic AI: task execution, LLM-integrated automation- Cite relevant PD customer examples or proof points (TEI, case studies, State of Ops)**6. Recommended Next Steps**- Suggest exploring specific PagerDuty solutions tied to the company’s initiatives**7. Sources**- Cite all public references and links usedGuidelines:- Do not fabricate executive names or initiatives- Be consultative, data-driven, and tight — 2–4 bullets per section- Cite sources and metrics when possible (e.g., “800% ROI per Forrester TEI”)"""try:response = client.chat.completions.create(model="gpt-4-turbo",messages=[{"role": "user", "content": prompt}])return response.choices[0].message.contentexcept Exception as e:return f"Failed to generate RTM for {company}: {str(e)}"def generate_prospecting_message(prospect_context, persona, linkedin_url, enriched_context, rtm_text, workspace="unknown", is_followup=False):prompt = f"""You are drafting a personalized outbound message for a senior enterprise salesperson at PagerDuty. The goal is to create a compelling reason for the recipient to respond and take a meeting.**Guidelines:**- Write in a natural, confident tone — avoid clichés like "Hope you're doing well" or "I'm reaching out because..."- Do *not* refer to the recipient’s title or role directly.- Use the prospect and company context as if you’ve done deep research.- Connect PagerDuty’s capabilities to the prospect’s likely challenges or initiatives.- Anchor the message in business value — not features.- End with a clear, relevant, and non-pushy ask to connect.**Prospect Information:**LinkedIn: {linkedin_url}Context: {prospect_context}**Persona (optional):**{persona}**Account Research:**{enriched_context}**Reason to Meet Summary:**{rtm_text}**Now write the message with this format:**Subject: <Insert compelling subject line — make it personal, strategic, or curiosity-driven>Body:<Open with a hook that shows you understand them><Bridge into how PagerDuty can help based on what they care about><Include a subtle insight or proof point><Ask for a quick conversation — make it relevant and low-pressure>Sign off as if from a real rep (no signature block needed)."""try:response = client.chat.completions.create(model="gpt-4-turbo",messages=[{"role": "user", "content": prompt}],)return response.choices[0].message.contentexcept Exception as e:return f"Failed to generate message: {str(e)}"def sanitize_linkedin_url(url):if "linkedin.com" not in url:return urlmatch = re.search(r"/in/([^/?&]+)", url)if match:return f"https://www.linkedin.com/in/{match.group(1)}"match_alt = re.search(r"linkedin.com/profile/view\?id=([^&]+)", url)if match_alt:return f"https://www.linkedin.com/profile/view?id={match_alt.group(1)}"return urldef log_event(workspace, event_type):log_path = f"usage_log_{workspace}.json"event = {"event": event_type, "timestamp": datetime.utcnow().isoformat()}if os.path.exists(log_path):with open(log_path, "r") as f:data = json.load(f)else:data = []data.append(event)with open(log_path, "w") as f:json.dump(data, f, indent=2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import openaiimport reimport jsonimport osimport timeclient = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))def sanitize_linkedin_url(url):if not url:return ""match = re.search(r"/in/([^/?]+)", url)if match:return f"https://www.linkedin.com/in/{match.group(1)}"match = re.search(r"profileUrn=urn:li:fsd_profile:(\w+)", url)if match:return f"https://www.linkedin.com/in/{match.group(1)}"return urldef generate_rtm(company, website, workspace=None):prompt = f"""You are an expert enterprise researcher helping a sales team uncover strategic business insights.Please generate a comprehensive Reason-to-Meet (RTM) report for the following company:Company: {company}Website: {website}Follow this structure:1. Company Overview2. Business Breakdown3. Strategic Initiatives4. Executive Team5. Challenges6. How PagerDuty Can Help7. SourcesUse recent, factual insights from reputable public sources only. Do not speculate. Align your analysis to PagerDuty’s value proposition based on the uploaded resources.Respond in clean markdown format with section headers and readable bullets.Cite sources after each section."""response = client.chat.completions.create(model="gpt-4-turbo",messages=[{"role": "user", "content": prompt}])return response.choices[0].message.content.strip()def generate_prospecting_message(context, persona, linkedin_url, enriched_context, rtm_report, workspace=None, is_followup=False):context_type = "follow-up" if is_followup else "first-touch"base_prompt = f"""You are writing a short, strategic {context_type} email to a prospect.Your goal is to:- Show you understand the company’s strategic initiatives and challenges- Relate to what they’re working on using thoughtful insight (not product pitching)- Connect to their likely role in those efforts- Invite a quick, casual conversationAvoid listing product features. Do not reference PagerDuty directly unless naturally relevant. Use insight and empathy, not a pitch.Tone should be confident, smart, and curious — not salesy or overly formal.Include:- A clear opener that ties to something observed in the Reason to Meet report- A strategic angle or insight that shows you understand their world- A crisp, conversational CTA (e.g., “open to comparing notes?”)---Prospect Info:{enriched_context}LinkedIn: {linkedin_url}---Reason to Meet (RTM) Report:{rtm_report}"""response = client.chat.completions.create(model="gpt-4-turbo",messages=[{"role": "user", "content": base_prompt}])return response.choices[0].message.content.strip()def log_event(workspace, event_type):ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())log = {"time": ts, "workspace": workspace, "event": event_type}log_file = "usage_log.json"if os.path.exists(log_file):with open(log_file, "r") as f:data = json.load(f)else:data = []data.append(log)with open(log_file, "w") as f:json.dump(data, f, indent=2)
utils.py+78-111