route.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { NextResponse, type NextRequest } from "next/server";
  2. import OpenAI from "openai";
  3. import emojiMap from "unicode-emoji-json";
  4. import { fuzzySearch } from "@/lib/fuzzySearch";
  5. const MAX_PROMPT = 80;
  6. function firstGrapheme(text: string) {
  7. const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
  8. for (const { segment } of segmenter.segment(text.trim())) return segment;
  9. return "";
  10. }
  11. export async function POST(req: NextRequest) {
  12. const body = await req.json().catch(() => null);
  13. const prompt =
  14. typeof body?.prompt === "string"
  15. ? body.prompt.trim().slice(0, MAX_PROMPT)
  16. : "";
  17. if (!prompt) {
  18. return NextResponse.json(
  19. { message: "Prompt is required" },
  20. { status: 400 },
  21. );
  22. }
  23. try {
  24. const openai = new OpenAI();
  25. const completion = await openai.chat.completions.create({
  26. model: "gpt-4o-mini",
  27. max_tokens: 8,
  28. messages: [
  29. {
  30. role: "system",
  31. content:
  32. "Reply with exactly one emoji that best matches the user's text. No words.",
  33. },
  34. { role: "user", content: prompt },
  35. ],
  36. });
  37. const emoji = firstGrapheme(completion.choices[0]?.message?.content ?? "");
  38. const entry =
  39. emojiMap[emoji as keyof typeof emojiMap] ??
  40. emojiMap[emoji.replace(/️/g, "") as keyof typeof emojiMap];
  41. const match = entry ? fuzzySearch(entry.name) : null;
  42. return NextResponse.json(
  43. { emoji, name: entry?.name ?? null, url: match?.url ?? null },
  44. { status: match ? 200 : 404 },
  45. );
  46. } catch (error: unknown) {
  47. const message = error instanceof Error ? error.message : "Unknown error";
  48. return NextResponse.json(
  49. { message: "Error generating completion", error: message },
  50. { status: 500 },
  51. );
  52. }
  53. }