import axios from 'axios'; import { z } from 'zod'; export class LegalQuestionService { private readonly apiKey: string; private readonly apiUrl: string; constructor() { this.apiKey = process.env.PERPLEXITY_API_KEY || ''; this.apiUrl = 'https://api.perplexity.ai/chat/completions'; if (!this.apiKey) { throw new Error('PERPLEXITY_API_KEY environment variable is not set'); } } async getLegalAnswer(question: string): Promise { try { const response = await axios.post( this.apiUrl, { model: 'sonar-medium-online', messages: [ { role: 'system', content: 'You are a legal expert assistant. Provide clear, accurate, and helpful legal information. Remember to include appropriate disclaimers when necessary.' }, { role: 'user', content: question } ] }, { headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' } } ); const responseSchema = z.object({ choices: z.array(z.object({ message: z.object({ content: z.string() }) })) }); const validatedResponse = responseSchema.parse(response.data); return validatedResponse.choices[0].message.content; } catch (error) { console.error('Error getting legal answer:', error); throw new Error('Failed to get legal answer'); } } }