Noam
CDCloudflare Developers
•Created by Noam on 11/16/2024 in #pages-help
Failed to load resource: the server responded with a status of 500 ()
I am using Atsro trying to make an endpoint that accepts a message that returns a response. Here is the code:
import type { APIContext } from 'astro';
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: import.meta.env.OPENAI_API_KEY,
});
const ASSISTANT_ID = import.meta.env.ASSISTANT_ID;
async function createAndRunThread(message: string) {
const thread = await openai.beta.threads.create({
messages: [{ role: 'user', content: message }],
});
const run = await openai.beta.threads.runs.createAndPoll(thread.id, {
assistant_id: ASSISTANT_ID,
});
if (run.status === 'completed') {
const messages = await openai.beta.threads.messages.list(thread.id);
const assistantMessage = messages.getPaginatedItems().find(msg => msg.role === 'assistant');
// Extract text content and clean up citations let content = assistantMessage?.content[0]?.type === 'text' ? assistantMessage.content[0].text.value : '';
// Remove citations using regex content = content.replace(/【[^】]*】/g, ''); return { content }; } throw new Error(
// Extract text content and clean up citations let content = assistantMessage?.content[0]?.type === 'text' ? assistantMessage.content[0].text.value : '';
// Remove citations using regex content = content.replace(/【[^】]*】/g, ''); return { content }; } throw new Error(
Run failed with status: ${run.status}
);
}
export async function GET({ url }: APIContext) {
try {
const message = url.searchParams.get('message');
if (!message) {
throw new Error('Message is required');
}
const thread = await createAndRunThread(message);
return new Response(JSON.stringify(thread), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred';
return new Response(JSON.stringify({ error: errorMessage }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}
Has anyone solve this issue? Previous comments haven't provided solutions that worked.1 replies