File size: 2,212 Bytes
02cc7f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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