|
| 1 | +import { config } from './config.js'; |
| 2 | + |
| 3 | +const API_KEY = 'API_KEY'; |
| 4 | + |
| 5 | +interface Message { |
| 6 | + role: 'system' | 'user' | 'assistant'; |
| 7 | + content: string; |
| 8 | +} |
| 9 | + |
| 10 | +interface Completion { |
| 11 | + Content: string | null; |
| 12 | + TokenUsage: number | undefined; |
| 13 | +} |
| 14 | + |
| 15 | +interface ConnectorResponse { |
| 16 | + Completions: Completion[]; |
| 17 | + ModelType: string; |
| 18 | +} |
| 19 | + |
| 20 | +interface PreplexiteResponse { |
| 21 | + id: string; |
| 22 | + model: string; |
| 23 | + created: number; |
| 24 | + usage: { |
| 25 | + prompt_tokens: number; |
| 26 | + completion_tokens: number; |
| 27 | + total_tokens: number; |
| 28 | + }; |
| 29 | + object: string; |
| 30 | + choices: { |
| 31 | + index: number; |
| 32 | + finish_reason: string; |
| 33 | + message: { |
| 34 | + role: string; |
| 35 | + content: string; |
| 36 | + }; |
| 37 | + delta: { |
| 38 | + role: string; |
| 39 | + content: string; |
| 40 | + }; |
| 41 | + }[]; |
| 42 | +} |
| 43 | + |
| 44 | +const mapToResponse = (outputs: PreplexiteResponse[]): ConnectorResponse => { |
| 45 | + return { |
| 46 | + Completions: outputs.map((output) => ({ |
| 47 | + Content: output.choices[0].message.content, |
| 48 | + TokenUsage: output.usage.total_tokens, |
| 49 | + })), |
| 50 | + ModelType: outputs[0].model, |
| 51 | + }; |
| 52 | +}; |
| 53 | + |
| 54 | +async function main( |
| 55 | + model: string, |
| 56 | + prompts: string[], |
| 57 | + properties: Record<string, unknown>, |
| 58 | + settings: Record<string, unknown>, |
| 59 | +): Promise<ConnectorResponse> { |
| 60 | + const apiKey = settings?.[API_KEY] as string; |
| 61 | + |
| 62 | + const messageHistory: Message[] = []; |
| 63 | + const outputs: PreplexiteResponse[] = []; |
| 64 | + |
| 65 | + try { |
| 66 | + for (const prompt of prompts) { |
| 67 | + messageHistory.push({ role: 'user', content: prompt }); |
| 68 | + |
| 69 | + const response = await fetch( |
| 70 | + 'https://api.perplexity.ai/chat/completions', |
| 71 | + { |
| 72 | + method: 'POST', |
| 73 | + headers: { |
| 74 | + 'Content-Type': 'application/json', |
| 75 | + Authorization: `Bearer ${apiKey}`, |
| 76 | + }, |
| 77 | + body: JSON.stringify({ |
| 78 | + model: model, |
| 79 | + messages: messageHistory, |
| 80 | + ...properties, |
| 81 | + }), |
| 82 | + }, |
| 83 | + ); |
| 84 | + |
| 85 | + const data: PreplexiteResponse = await response.json(); |
| 86 | + |
| 87 | + const assistantResponse = data.choices[0].message.content; |
| 88 | + |
| 89 | + messageHistory.push({ role: 'assistant', content: assistantResponse }); |
| 90 | + |
| 91 | + outputs.push(data); |
| 92 | + } |
| 93 | + |
| 94 | + return mapToResponse(outputs); |
| 95 | + } catch (error) { |
| 96 | + console.error('Error in main function:', error); |
| 97 | + throw error; |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +export { main, config }; |
0 commit comments