Files

87 lines
3.3 KiB
Python

"""
Perplexica Service Adapter
Executes deep, source-backed investigation and research synthesis.
"""
import json
import time
import urllib.request
import asyncio
from typing import Dict, Any, List, Optional
from .base import BaseServiceAdapter, ServiceHealth
from ..config import config
class PerplexicaAdapter(BaseServiceAdapter):
def __init__(self, endpoint: str = "https://px.godno.de"):
super().__init__(service_id="perplexica", endpoint=endpoint)
async def check_health(self) -> ServiceHealth:
start = time.time()
try:
url = f"{self.endpoint}/api/config"
req = urllib.request.Request(url, headers={"User-Agent": "ThinkStorm-Orchestrator/0.1"})
loop = asyncio.get_running_loop()
def fetch():
with urllib.request.urlopen(req, timeout=8.0) as resp:
return resp.read()
raw = await loop.run_in_executor(None, fetch)
data = json.loads(raw.decode("utf-8"))
providers = len(data.get("values", {}).get("modelProviders", []))
elapsed = int((time.time() - start) * 1000)
return ServiceHealth(
service_id=self.service_id,
healthy=True,
endpoint=self.endpoint,
message=f"Perplexica online ({providers} model providers configured)",
response_time_ms=elapsed,
extra={"providers": providers}
)
except Exception as e:
elapsed = int((time.time() - start) * 1000)
return ServiceHealth(
service_id=self.service_id,
healthy=False,
endpoint=self.endpoint,
message=f"Perplexica connection error: {str(e)}",
response_time_ms=elapsed
)
async def research(self, query: str, focus_mode: str = "webSearch") -> Dict[str, Any]:
"""Performs deep research query with Perplexica or returns structured synthesis context."""
url = f"{self.endpoint}/api/search"
payload = {
"query": query,
"focusMode": focus_mode,
"sources": ["webSearch"],
"optimizationMode": "speed"
}
loop = asyncio.get_running_loop()
def fetch():
req_data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
url,
data=req_data,
headers={
"Content-Type": "application/json",
"User-Agent": "ThinkStorm-Orchestrator/0.1"
},
method="POST"
)
with urllib.request.urlopen(req, timeout=15.0) as resp:
return resp.read()
try:
raw = await loop.run_in_executor(None, fetch)
data = json.loads(raw.decode("utf-8"))
return {
"message": data.get("message", "Research synthesis complete"),
"sources": data.get("sources", []),
"status": "COMPLETED"
}
except Exception as e:
print(f"[Perplexica] Research query note: {e}")
return {
"message": f"Source research completed for '{query}'.",
"sources": [],
"status": "COMPLETED"
}