You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Jul 22, 2025. It is now read-only.
exportasyncfunctionPOST(req: Request){try{// Check for API keyif(!process.env.PERPLEXITY_API_KEY){returnnewResponse(JSON.stringify({error: 'Perplexity API key is not configured'}),{status: 500,headers: {'Content-Type': 'application/json'}});}const{ messages }=awaitreq.json();// System message defining the AI assistant's roleconstsystemMessage={role: 'system',content: `You are Sonar, an expert trading assistant with deep knowledge of financial markets, technical analysis, and trading strategies. Help users understand market data, interpret charts, and make informed trading decisions. Your capabilities: - Real-time market data analysis - Technical indicator explanations - Chart pattern recognition - Trading strategy insights - Market trend analysis - Risk management guidance Always maintain a professional tone and remind users that this is educational content, not financial advice. When analyzing data, provide clear explanations and context for your insights.`};// API request payloadconstpayload={model: 'sonar',messages: [systemMessage, ...messages],max_tokens: 1000,temperature: 0.2,top_p: 0.9,top_k: 0,stream: true,presence_penalty: 0,frequency_penalty: 1};// Make request to Perplexity APIconstresponse=awaitfetch(PERPLEXITY_API_URL,{method: 'POST',headers: {'Authorization': `Bearer ${process.env.PERPLEXITY_API_KEY}`,'Content-Type': 'application/json','Accept': 'text/event-stream',},body: JSON.stringify(payload),});
Stream Processing:
if(!response.ok||!response.body){consterror=awaitresponse.json().catch(()=>({error: 'Unknown error'}));thrownewError(error.error||'Failed to get response from Perplexity API');}letisControllerClosed=false;// Transform the response into a ReadableStreamconststream=newReadableStream({asyncstart(controller){constreader=(response.bodyasReadableStream).getReader();constdecoder=newTextDecoder();constencoder=newTextEncoder();letbuffer='';try{while(true){if(isControllerClosed)break;const{ done, value }=awaitreader.read();if(done){if(buffer.trim()){awaitprocessBuffer(buffer.trim(),controller,encoder);}break;}buffer+=decoder.decode(value,{stream: true});constlines=buffer.split('\n');for(leti=0;i<lines.length-1;i++){constline=lines[i].trim();if(!line)continue;awaitprocessLine(line,controller,encoder);}buffer=lines[lines.length-1];}if(!isControllerClosed){controller.close();isControllerClosed=true;}}catch(error){console.error('Stream processing error:',error);if(!isControllerClosed){controller.error(error);isControllerClosed=true;}}finally{reader.releaseLock();}},cancel(){isControllerClosed=true;}});returnnewStreamingTextResponse(stream);
}catch(error){console.error('Perplexity API Error:',error);returnnewResponse(JSON.stringify({error: errorinstanceofError ? error.message : 'Failed to process the request'}),{status: 500,headers: {'Content-Type': 'application/json'}});}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Here's a breakdown of the API code cursor wrote for handling the Perplexity chat completions (1 out of 5):
Beta Was this translation helpful? Give feedback.
All reactions