Vercel Serverless Functions Help
Unanswered
Black carpenter ant posted this in #help-forum
Black carpenter antOP
I have a function like this
the vercel serverless functions does only till the 2nd one and the request just has marked as "200"
the time it took the serverless functions is only 440ms/10s
What's causing the issue? Vercel or my code?
I'm using AI at third event
(First event)
(Second event)
(Third event)the vercel serverless functions does only till the 2nd one and the request just has marked as "200"
the time it took the serverless functions is only 440ms/10s
What's causing the issue? Vercel or my code?
I'm using AI at third event
26 Replies
Black carpenter antOP
ping me when replying
@Black carpenter ant I have a function like this
js
(First event)
(Second event)
(Third event)
the vercel serverless functions does only till the 2nd one and the request just has marked as "200"
the time it took the serverless functions is only 440ms/10s
What's causing the issue? Vercel or my code?
I'm using AI at third event
Short-tailed Hawk
if the response is 200 and the third event isn’t happening then you gotta check your code logic cuz it might be set up so the third event doesn’t even get called
@Short-tailed Hawk if the response is 200 and the third event isn’t happening then you gotta check your code logic cuz it might be set up so the third event doesn’t even get called
Black carpenter antOP
Here's a look at how my code works
export default async function handler(req: VercelRequest, res: VercelResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' }); // Method check
}
try {
const rawBody = await parseBody(req); // Parse body
const body = JSON.parse(rawBody); // Convert to JSON
if (!validateRequest(req, rawBody)) {
return res.status(401).json({ error: 'Invalid signature' }); // Validate request
}
if (isPingInteraction(body)) {
return res.json(handlePing()); // Handle ping
}
if (isCommand(body)) {
const options = extractCommandOptions(body); // Extract options
sendDeferredResponse(res, options); // Send deferred response
const response = await processCommand(options); // Process command
updateResponse(body, response); // Update response
} else {
return res.json(handleUnknownCommand()); // Unknown command
}
} catch (error) {
return handleError(res, error); // Error handling
}
}I don't think there is any kind of errors in it that's stopping it from running third event
Short-tailed Hawk
well if the iscommand(body) is returning false then that code wont be ran
@Short-tailed Hawk well if the iscommand(body) is returning false then that code wont be ran
Black carpenter antOP
it is running till processCommand function
@Black carpenter ant it is running till processCommand function
Short-tailed Hawk
console log what the response is
@Short-tailed Hawk console log what the response is
Black carpenter antOP
it returns it correctly
but it just didn't run the last function
@Black carpenter ant it returns it correctly
Short-tailed Hawk
console log everything and check if they’re working / check if your if statements return false or true / check if it works while locally hosted
@Short-tailed Hawk console log everything and check if they’re working / check if your if statements return false or true / check if it works while locally hosted
Black carpenter antOP
I checked, and I found that this code is where the error is occurring.
import { createGoogleGenerativeAI } from '@ai-sdk/google';
import { groq } from '@ai-sdk/groq';
import { generateText } from 'ai';
import { log } from '../utils/log';
const systemPrompt = "..";
export interface AIResponse {
success: boolean;
response?: string;
error?: string;
}
if (!process.env.GOOGLE_API_KEY) {
throw new Error('GOOGLE_API_KEY is not set');
}
export async function generateResponse(prompt: string): Promise<AIResponse> {
try {
log('Generate event called');
[the code only returunt till the generate event called log]
const { text } = await generateText({
model: groq('llama-3.3-70b-versatile'),
system: systemPrompt,
maxTokens: 1620,
prompt
});
[I think error is here]
log('Response generated: ' + text);
return {
success: true,
response: text
};
} catch (error) {
console.error('AI Service Error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
};
}
}@Short-tailed Hawk okay now search for docs where u can find the code you’re trying to apply without errors
Black carpenter antOP
i viewed, still not found the solution that's why sent here
i have tried my best 😭
Short-tailed Hawk
check if the env keys have the correct values and console log them in your function to see if they’re there
@Short-tailed Hawk check if the env keys have the correct values and console log them in your function to see if they’re there
Black carpenter antOP
they have, I'm using a get request to debug them
also maybe this is working fine too
cuz I'm using this generate response function on a get request to debug and it returns the response fine
Short-tailed Hawk
if it works then great
@Short-tailed Hawk if it works then great
Black carpenter antOP
that's working but this isn't, it only runs till the generate event called in the generate response function, then it just stops and makes it as 200.
While when debugging the generate response function with another simple get request, it works fine!?
While when debugging the generate response function with another simple get request, it works fine!?
...
export default async function handler(req: VercelRequest, res: VercelResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
log('Request created')
const rawBody = await getRawBody(req);
const body: DiscordInteraction = JSON.parse(rawBody.toString());
log('Body: ' + JSON.stringify(body));
const isValidRequest = await verifyDiscordRequest(req, rawBody.toString());
if (!isValidRequest) {
log('Invalid Request')
return res.status(401).json({ error: 'Invalid request signature' });
}
// Handle ping
if (body.type === InteractionType.PING) {
log('Ping interaction received');
return res.json({ type: InteractionResponseType.PONG });
}...
const { name, options = [] } = body.data || {};
if (name === 'chat') {
log('Command interaction created for command /chat');
...
log('Prompt: ' + prompt);
// Send deferred response first
const deferredResponse: InteractionResponse = {
type: InteractionResponseType.DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE,
data: {
flags: ephemeral ? 64 : 0
}
};
// Send the deferred response
await res.json(deferredResponse);
log('Deferred response sent');
try {
log('"generateResponse" function called (external)');
// Generate AI response
const aiResponse = await generateResponse(prompt);
log('Response received: ' + aiResponse);
// Update message with AI response const webhookUrl = `https://discord.com/api/v10/webhooks/${process.env.DISCORD_APP_ID}/${body.token}/messages/@original`;
// Add error handling and retry logic for the webhook call
let retries = 3;
while (retries > 0) {
try {
const result = await fetch(webhookUrl, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bot ${process.env.DISCORD_TOKEN}` // Add bot token for authentication
},
body: JSON.stringify({
content: aiResponse.response ?? `Error: ${aiResponse.error ?? 'Failed to generate response'}`,
flags: ephemeral ? 64 : 0
}),
});
log(`Webhook response status: ${result.status}`);
if (result.ok) {
log('Successfully edited @original message');
break;
} else {
const errorText = await result.text();
log(`Failed to update message: ${errorText}`);
throw new Error(`Discord API error: ${errorText}`);
}
} catch (error) {
log(`Webhook attempt failed: ${error.message}`);
retries--;
if (retries === 0) throw error;
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1s between retries
}
}
...@Short-tailed Hawk send the code where you're setting up response(200)
Black carpenter antOP
I ain't setting it 200 anywhere
@Black carpenter ant I ain't setting it 200 anywhere
Short-tailed Hawk
so if you aint sending responses back what are u trynna do, just run backend code without sending any response?
@Short-tailed Hawk so if you aint sending responses back what are u trynna do, just run backend code without sending any response?
Black carpenter antOP
it's a discord bot