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)}"