route.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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-6-luna",
  27. reasoning_effort: "none",
  28. service_tier: "fast",
  29. max_completion_tokens: 8,
  30. messages: [
  31. {
  32. role: "system",
  33. content:
  34. "Reply with exactly one emoji that best matches the user's text. No words.",
  35. },
  36. { role: "user", content: prompt },
  37. ],
  38. });
  39. const emoji = firstGrapheme(completion.choices[0]?.message?.content ?? "");
  40. const entry =
  41. emojiMap[emoji as keyof typeof emojiMap] ??
  42. emojiMap[emoji.replace(/️/g, "") as keyof typeof emojiMap];
  43. const match = entry ? fuzzySearch(entry.name) : null;
  44. return NextResponse.json(
  45. { emoji, name: entry?.name ?? null, url: match?.url ?? null },
  46. { status: match ? 200 : 404 },
  47. );
  48. } catch (error: unknown) {
  49. const message = error instanceof Error ? error.message : "Unknown error";
  50. return NextResponse.json(
  51. { message: "Error generating completion", error: message },
  52. { status: 500 },
  53. );
  54. }
  55. }