import os import requests import json from dotenv import load_dotenv load_dotenv() PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY") def research_company(company_name: str) -> dict: """ Uses Perplexity AI to conduct deep web research on a company's environmental impact. Returns: { "description": str, "findings": list, "sentiment": str, "citations": list } """ if not PERPLEXITY_API_KEY: print("Warning: PERPLEXITY_API_KEY not found.") return None url = "https://api.perplexity.ai/chat/completions" # Prompt designed to extract structured data compatible with our existing analysis system_prompt = "You are an environmental analyst. Research the target company and return a JSON object with: 'description' (factual summaries), 'findings' (list of 5 key controversies or achievements), 'sentiment' (Positive/Negative/Mixed), 'citations' (list of source URLs), and 'recommendations' (object with keys 'for_customers', 'for_investors', 'for_company_leadership', each a list of 3 strings)." user_prompt = f"Research the environmental track record of '{company_name}'. Focus on emissions, greenwashing, and sustainability 2023-2025." payload = { "model": "sonar", "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt} ], "temperature": 0.2 } headers = { "Authorization": f"Bearer {PERPLEXITY_API_KEY}", "Content-Type": "application/json" } try: response = requests.post(url, json=payload, headers=headers) response.raise_for_status() result = response.json() content = result['choices'][0]['message']['content'] citations = result.get('citations', []) # Clean JSON markdown if present if content.startswith("```json"): content = content[7:] if content.endswith("```"): content = content[:-3] data = json.loads(content) data['citations'] = citations # Ensure citations are attached return data except Exception as e: print(f"Perplexity API Error: {e}") return None