import config from '../config'; import { store } from '../utils/tempStore'; interface LegalQuestion { question: string; language: string; location: string; } export class PerplexityService { private readonly apiKey: string; private readonly baseUrl: string = 'https://api.perplexity.ai/sonar/v1'; constructor() { this.apiKey = config.perplexityApiKey; } async askLegalQuestion({ question, language, location }: LegalQuestion): Promise { const prompt = this.constructLegalPrompt(question, language, location); try { const response = await fetch(`${this.baseUrl}/query`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'sonar-medium-online', query: prompt, temperature: 0.7, }), }); if (!response.ok) { throw new Error(`Perplexity API error: ${response.statusText}`); } const data = await response.json(); // Store the query and response const queryId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; store.saveSonarQuery(queryId, prompt, data); return { answer: data.text, queryId, }; } catch (error) { console.error('Error calling Perplexity API:', error); throw new Error('Failed to get answer from Perplexity API'); } } private constructLegalPrompt(question: string, language: string, location: string): string { return `As a legal expert, provide advice about the following question, considering the specific location (${location}) and answer in ${language} language. Question: ${question} Important: 1. Consider local laws and regulations specific to ${location} 2. Provide clear, actionable advice 3. Include relevant legal references when possible 4. Add a disclaimer about consulting with a local legal professional 5. Keep the response concise but comprehensive`; } } export const perplexityService = new PerplexityService();