Snippet
typescript
Sitecore
Sitecore AI
Code Sample
Copy 1// app/api/summarize-sitecore/route.ts2import { NextRequest, NextResponse } from "next/server";3const QUERY = `4 query ArticleByPath($path: String!, $language: String!) {5 item(path: $path, language: $language) {6 title: field(name: "Title") { value }7 body: field(name: "Content") { value }8 }9 }10`;11export async function POST(request: NextRequest) {12 const { path, language = "en" } = await request.json();13 const sitecore = await fetch(process.env.SITECORE_GRAPHQL_ENDPOINT!, {14 method: "POST",15 headers: {16 "Content-Type": "application/json",17 sc_apikey: process.env.SITECORE_EDGE_API_KEY!,18 },19 body: JSON.stringify({ query: QUERY, variables: { path, language } }),20 }).then((res) => res.json());21 const item = sitecore?.data?.item;22 if (!item?.body?.value) {23 return NextResponse.json({ error: "Item not found" }, { status: 404 });24 }25 const ai = await fetch("https://api.openai.com/v1/chat/completions", {26 method: "POST",27 headers: {28 "Content-Type": "application/json",29 Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,30 },31 body: JSON.stringify({32 model: "gpt-4o-mini",33 temperature: 0.2,34 messages: [35 {36 role: "system",37 content: "Summarize Sitecore page content in 3 bullet points.",38 },39 {40 role: "user",41 content: `Title: ${item.title?.value ?? "Untitled"}\n\n${item.body.value}`,42 },43 ],44 }),45 }).then((res) => res.json());46 return NextResponse.json({47 summary: ai.choices?.[0]?.message?.content ?? "",48 });49}