Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/document-search/frontend/src/app/api/search/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";

const API_KEY = process.env.SHAPED_API_KEY ?? "";
const QUERY_ENDPOINT =
"https://api.shaped.ai/v1/models/demo___blog_semantic_search/query";
"https://api.shaped.ai/v2/models/demo___blog_semantic_search/query";

interface MainImage {
fileId: string;
Expand Down
174 changes: 90 additions & 84 deletions apps/movie-recommendations/frontend/package-lock.json

Large diffs are not rendered by default.

11 changes: 6 additions & 5 deletions apps/movie-recommendations/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build --turbopack",
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint",
"deploy": "vercel --prod"
Expand Down Expand Up @@ -48,11 +48,11 @@
"input-otp": "^1.4.2",
"lodash": "^4.17.21",
"lucide-react": "^0.545.0",
"next": "15.5.7",
"next": "^16.1.6",
"next-themes": "^0.4.6",
"react": "19.1.0",
"react": "^19.2.4",
"react-day-picker": "^9.11.1",
"react-dom": "19.1.0",
"react-dom": "^19.2.4",
"react-hook-form": "^7.64.0",
"react-resizable-panels": "^3.0.6",
"react-router-dom": "^7.9.4",
Expand All @@ -70,6 +70,7 @@
"@types/react": "^19",
"@types/react-dom": "^19",
"autoprefixer": "^10.4.21",
"baseline-browser-mapping": "^2.9.19",
"eslint": "^9",
"eslint-config-next": "15.5.4",
"kill-port": "^2.0.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { NextResponse } from "next/server";
import { SHAPED_API_ENDPOINTS } from "@/constants/shaped";
import { getInteractionsFromServerCookie } from "@/lib/interactions";

const token = process.env.SHAPED_API_KEY ?? "";

export async function POST(req: Request) {
try {
// Get interactions from cookies
const cookieHeader = req.headers.get('cookie') || '';
const interactions = getInteractionsFromServerCookie(cookieHeader);

// Get userId from cookies
const cookies = cookieHeader.split(';').reduce((acc, cookie) => {
const [name, value] = cookie.trim().split('=');
acc[name] = value;
return acc;
}, {} as Record<string, string>);
const userId = cookies['movie_app_user_id'] || null;

const shapedRequestBody = {
return_metadata: true,
query: `SELECT * FROM similarity(
embedding_ref="collaborative_embedding",
limit=50,
encoder='interaction_round_robin',
input_user_id='$user_id'
), column_order(
columns='_derived_interaction_count desc'
)
ORDER BY score(expression='click_through_rate', input_user_id='$user_id')`,
parameters: {
user_id: userId
}
};

console.log("Shaped API request payload:", shapedRequestBody);

// Call Shaped API
const response = await fetch(SHAPED_API_ENDPOINTS.QUERY_V2, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": token,
},
body: JSON.stringify(shapedRequestBody),
});

if (!response.ok) {
const text = await response.text();
console.error(`Shaped API error (${response.status}):`, text);
return NextResponse.json(
{ ok: false, error: `Shaped API error (${response.status}): ${text}` },
{ status: response.status }
);
}

const data = await response.json();
console.log({data})

// Debug logging for type errors
if (!data.results) {
console.error("DEBUG: Shaped API response missing 'results' field. Response structure:", JSON.stringify(data, null, 2));
return NextResponse.json(
{ ok: false, error: "Invalid API response: missing 'results' field" },
{ status: 500 }
);
}

if (!Array.isArray(data.results)) {
console.error("DEBUG: Shaped API 'results' is not an array. Type:", typeof data.results, "Value:", JSON.stringify(data.results, null, 2));
return NextResponse.json(
{ ok: false, error: "Invalid API response: 'results' is not an array" },
{ status: 500 }
);
}

// Validate that items have expected structure
const invalidItems = data.results.filter((item: any) => {
if (!item || (!item.id && !item.item_id)) {
console.error("DEBUG: Item missing id/item_id:", JSON.stringify(item, null, 2));
return true;
}
if (!item.metadata || typeof item.metadata !== 'object') {
console.error("DEBUG: Item missing or invalid metadata:", JSON.stringify(item, null, 2));
return true;
}
return false;
});

if (invalidItems.length > 0) {
console.error(`DEBUG: Found ${invalidItems.length} items with invalid structure out of ${data.results.length} total items`);
}

return NextResponse.json({ ok: true, results: data.results }, { status: 200 });
} catch (error) {
console.error("Error in /api/movies/for-you:", error);
return NextResponse.json(
{ ok: false, error: error instanceof Error ? error.message : "Unknown error" },
{ status: 500 }
);
}
}

135 changes: 135 additions & 0 deletions apps/movie-recommendations/frontend/src/app/api/movies/genre/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { NextResponse } from "next/server";
import { SHAPED_API_ENDPOINTS } from "@/constants/shaped";

const token = process.env.SHAPED_API_KEY ?? "";

const VALID_GENRES = [
"Action",
"Adventure",
"Animation",
"Childrens",
"Comedy",
"Crime",
"Documentary",
"Drama",
"Fantasy",
"Film_Noir",
"Horror",
"Musical",
"Mystery",
"Romance",
"Sci-Fi",
"Thriller",
"War",
"Western",
];

export async function POST(req: Request) {
try {
const payload = await req.json();
const genre = payload?.genre;

const cookieHeader = req.headers.get("cookie") || "";
const cookies = cookieHeader.split(";").reduce((acc, cookie) => {
const [name, value] = cookie.trim().split("=");
if (name) acc[name] = value;
return acc;
}, {} as Record<string, string>);

const userId = cookies["movie_app_user_id"] || null;

if (!genre || typeof genre !== 'string') {
return NextResponse.json(
{ ok: false, error: "Bad request: genre is required and must be a string" },
{ status: 400 }
);
}

if (!VALID_GENRES.includes(genre)) {
return NextResponse.json(
{ ok: false, error: `Genre ${genre} not in dataset. Valid genres: ${VALID_GENRES.join(', ')}` },
{ status: 400 }
);
}

// Call Shaped API
const response = await fetch(SHAPED_API_ENDPOINTS.QUERY_V2, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": token,
},
body: JSON.stringify({
return_metadata: true,
query: `SELECT *
FROM filter(where='$filter_predicate')
ORDER BY score(
expression='0.4 * click_through_rate +\
0.6 * cosine_similarity(pooled_text_encoding(\
user.recent_interactions, pool_fn=''mean'', embedding_ref="description_content_embedding"\
), text_encoding(\
item, embedding_ref="description_content_embedding"\
))', input_user_id='$user_id')
LIMIT 20`,
parameters: {
filter_predicate: `array_has_any(genres, ['${genre}'])`,
user_id: userId ?? ''
},
}),
});

if (!response.ok) {
const text = await response.text();
console.error(`Error fetching ${genre} movies:`, response.status, response.statusText, text);
return NextResponse.json(
{ ok: false, error: `Shaped API error (${response.status}): ${text}` },
{ status: response.status }
);
}

const data = await response.json();

// Debug logging for type errors
if (!data.results) {
console.error(`DEBUG: Shaped API response missing 'results' field for genre ${genre}. Response structure:`, JSON.stringify(data, null, 2));
return NextResponse.json(
{ ok: false, error: "Invalid API response: missing 'results' field" },
{ status: 500 }
);
}

if (!Array.isArray(data.results)) {
console.error(`DEBUG: Shaped API 'results' is not an array for genre ${genre}. Type:`, typeof data.results, "Value:", JSON.stringify(data.results, null, 2));
return NextResponse.json(
{ ok: false, error: "Invalid API response: 'results' is not an array" },
{ status: 500 }
);
}

// Validate that items have expected structure
const invalidItems = data.results.filter((item: any) => {
if (!item || (!item.id && !item.item_id)) {
console.error(`DEBUG: Item missing id/item_id for genre ${genre}:`, JSON.stringify(item, null, 2));
return true;
}
if (!item.metadata || typeof item.metadata !== 'object') {
console.error(`DEBUG: Item missing or invalid metadata for genre ${genre}:`, JSON.stringify(item, null, 2));
return true;
}
return false;
});

if (invalidItems.length > 0) {
console.error(`DEBUG: Found ${invalidItems.length} items with invalid structure out of ${data.results.length} total items for genre ${genre}`);
}

return NextResponse.json({ ok: true, results: data.results }, { status: 200 });
} catch (error) {
console.error(`Error in /api/movies/genre:`, error);
return NextResponse.json(
{ ok: false, error: error instanceof Error ? error.message : "Unknown error" },
{ status: 500 }
);
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { NextResponse } from "next/server";
import { SHAPED_API_ENDPOINTS } from "@/constants/shaped";

const token = process.env.SHAPED_API_KEY ?? "";

export async function POST(req: Request) {
try {
// Get userId from cookies
const cookieHeader = req.headers.get("cookie") || "";
const cookies = cookieHeader.split(";").reduce((acc, cookie) => {
const [name, value] = cookie.trim().split("=");
if (name) acc[name] = value;
return acc;
}, {} as Record<string, string>);

const userId = cookies["movie_app_user_id"] || null;
console.log({userId})

const shapedRequestBody = {
return_metadata: true,
query: `SELECT * FROM column_order(columns='_derived_popular_rank ASC', limit=20)
ORDER BY score(expression='(click_through_rate - 1)', input_user_id='$user_id', input_interactions_item_ids='$interaction_item_ids')
LIMIT 10`,
parameters: {
user_id: userId,
interaction_item_ids: []
},
};

// Call Shaped API
const response = await fetch(SHAPED_API_ENDPOINTS.QUERY_V2, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": token,
},
body: JSON.stringify(shapedRequestBody),
});

if (!response.ok) {
const text = await response.text();
console.error(`Shaped API error (${response.status}):`, text);
return NextResponse.json(
{ ok: false, error: `Shaped API error (${response.status}): ${text}` },
{ status: response.status }
);
}

const data = await response.json();

// Debug logging for type errors
if (!data.results) {
console.error(
"DEBUG: Shaped API response missing 'results' field. Response structure:",
JSON.stringify(data, null, 2)
);
return NextResponse.json(
{ ok: false, error: "Invalid API response: missing 'results' field" },
{ status: 500 }
);
}

if (!Array.isArray(data.results)) {
console.error(
"DEBUG: Shaped API 'results' is not an array. Type:",
typeof data.results,
"Value:",
JSON.stringify(data.results, null, 2)
);
return NextResponse.json(
{ ok: false, error: "Invalid API response: 'results' is not an array" },
{ status: 500 }
);
}

// Validate that items have expected structure
const invalidItems = data.results.filter((item: any) => {
if (!item || (!item.id && !item.item_id)) {
console.error("DEBUG: Item missing id/item_id:", JSON.stringify(item, null, 2));
return true;
}
if (!item.metadata || typeof item.metadata !== "object") {
console.error(
"DEBUG: Item missing or invalid metadata:",
JSON.stringify(item, null, 2)
);
return true;
}
return false;
});

if (invalidItems.length > 0) {
console.error(
`DEBUG: Found ${invalidItems.length} items with invalid structure out of ${data.results.length} total items`
);
}

return NextResponse.json({ ok: true, results: data.results }, { status: 200 });
} catch (error) {
console.error("Error in /api/movies/trending:", error);
return NextResponse.json(
{ ok: false, error: error instanceof Error ? error.message : "Unknown error" },
{ status: 500 }
);
}
}

Loading