File size: 5,610 Bytes
50cadfc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import requests
import json

def call_perplexity_api(query: str, api_key: str, model: str):
    """Calls the Perplexity API with the provided query and parameters."""
    if not api_key:
        return "Error: Perplexity API not initialized. Please initialize it first."
    
    url = "https://api.perplexity.ai/chat/completions"
    
    # System prompt
    system_prompt = """
    You are a helpful AI assistant.

    Rules:
    1. Provide only the final answer. It is important that you do not include any explanation on the steps below.
    2. Do not show the intermediate steps information.

    Steps:
    1. Decide if the answer should be a brief sentence or a list of suggestions.
    2. If it is a list of suggestions, first, write a brief and natural introduction based on the original query.
    3. Followed by a list of suggestions, each suggestion should be split by two newlines.
    """
    
    payload = {
        "model": model,  # Use the selected model
        "messages": [
            {
                "role": "system",
                "content": system_prompt.strip()  # Add the system prompt
            },
            {
                "role": "user",
                "content": query
            }
        ],
        "max_tokens": 8000 if model in ["sonar-reasoning-pro", "sonar-pro"] else 1000,
        "temperature": 0.2,
        "top_p": 0.9,
        "search_domain_filter": None,
        "return_images": False,
        "return_related_questions": False,
        "search_recency_filter": "month",  # Limit recency of search to this month
        "top_k": 0,
        "stream": False,
        "presence_penalty": 0,
        "frequency_penalty": 1,
        "response_format": None
    }
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)
        return response.json()  # Return the JSON response
    except requests.exceptions.RequestException as e:
        # Provide detailed error information
        error_details = {
            "error_type": type(e).__name__,
            "error_message": str(e),
            "response_status_code": getattr(e.response, "status_code", None),
            "response_text": getattr(e.response, "text", None),
            "request_payload": payload,
            "request_headers": headers
        }
        return f"Request failed. Details:\n{json.dumps(error_details, indent=2)}"

def get_ai_research_papers(query: str, api_key: str, model: str) -> str:
    """A tool that fetches relevant AI research papers using Perplexity API."""
    try:
        response_json = call_perplexity_api(f"search AI research papers about: {query}", api_key, model)
        if isinstance(response_json, str):  # Error message
            return response_json
        
        if response_json and "choices" in response_json:
            content = response_json["choices"][0]["message"]["content"]
            citations = response_json.get("citations", [])
            citation_string = "\n".join([f"{i+1}. {citation}" for i, citation in enumerate(citations)])
            
            return f"AI Research Papers:\n{content}\n\nCitations:\n{citation_string if citation_string else 'No citations found.'}"
            
        return f"No relevant AI papers found for your query: {query}"
    except Exception as e:
        return f"Error fetching research papers: {str(e)}"

def summarize_paper(paper_title: str, api_key: str, model: str) -> str:
    """A tool that summarizes an AI research paper."""
    try:
        response_json = call_perplexity_api(f"Summarize AI research paper: {paper_title}", api_key, model)
        if isinstance(response_json, str):  # Error message
            return response_json
        
        if response_json and "choices" in response_json:
            content = response_json["choices"][0]["message"]["content"]
            return f"Summary of '{paper_title}':\n{content}"
        return f"Could not summarize paper '{paper_title}'"
    except Exception as e:
        return f"Error summarizing paper: {str(e)}"

def get_citation(paper_title: str, api_key: str, model: str) -> str:
    """A tool that generates a citation for an AI research paper."""
    try:
        response_json = call_perplexity_api(f"Generate citation for AI research paper: {paper_title}", api_key, model)
        if isinstance(response_json, str):  # Error message
            return response_json
         
        if response_json and "choices" in response_json:
            content = response_json["choices"][0]["message"]["content"]
            return f"Citation for '{paper_title}':\n{content}"
        return f"Could not generate citation for '{paper_title}'"
    except Exception as e:
        return f"Error generating citation: {str(e)}"

def explain_concept(concept: str, api_key: str, model: str) -> str:
    """A tool that explains an AI-related concept in simple terms."""
    try:
        response_json = call_perplexity_api(f"Explain the AI concept: {concept}", api_key, model)
        if isinstance(response_json, str):  # Error message
            return response_json
         
        if response_json and "choices" in response_json:
            content = response_json["choices"][0]["message"]["content"]
            return f"Explanation of {concept}:\n{content}"
        return f"Could not explain the concept '{concept}'"
    except Exception as e:
        return f"Error explaining concept: {str(e)}"