Skip to content

Commit

Permalink
refactor: handling new api response (#69)
Browse files Browse the repository at this point in the history
  • Loading branch information
maciejkrol18 authored Jan 2, 2025
2 parents 9113df3 + 2f52e23 commit 549f123
Show file tree
Hide file tree
Showing 7 changed files with 119 additions and 76 deletions.
16 changes: 8 additions & 8 deletions src/app/api/recommend/route.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import { NextResponse } from "next/server";

import { fetchData } from "@/lib/api";
import { mockFetch } from "@/lib/mock-fetch";
import type {
RawApiRecommendation,
RecommendationRequest,
RecommendationResponse,
} from "@/types/api-types";

export async function POST(request: Request) {
const body = (await request.json()) as RecommendationRequest;

const data = await fetchData<RawApiRecommendation>("/recommend/invoke", {
if (process.env.NODE_ENV === "development") {
const response = await mockFetch("/api/recommend");
return NextResponse.json(await response.json());
}

const data = await fetchData<RecommendationResponse>("/recommend/invoke", {
body: JSON.stringify(body),
method: "POST",
});

const result: RecommendationResponse = {
faculty: data.output.faculty,
question: data.output.question,
recommendation: data.output.recommendation,
};
return NextResponse.json(result);
return NextResponse.json(data);
}
27 changes: 14 additions & 13 deletions src/components/recommendation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { CircleX, LoaderPinwheel } from "lucide-react";
import { useEffect, useState } from "react";
import { v4 } from "uuid";

import { mockFetch } from "@/lib/mock-fetch";
import type { RecommendationResponse } from "@/types/api-types";
import type { Chat } from "@/types/chat";
import type { Supervisor as ISupervisor } from "@/types/supervisor";
Expand All @@ -19,21 +18,21 @@ function useRecommendationQuery(
return useQuery({
queryKey: ["recommendation", chat.uuid],
queryFn: async () => {
const response = await mockFetch("/api/recommend");
// const response = await fetch("/api/recommend", {
// method: "POST",
// body: JSON.stringify({
// input: { question: chat.prompt, faculty: chat.faculty },
// }),
// });
const response = await fetch("/api/recommend", {
method: "POST",
body: JSON.stringify({
input: { question: chat.prompt, faculty: chat.faculty },
}),
});

const data = (await response.json()) as RecommendationResponse;
const supervisorsWithUuid =
data.recommendation.recommended_supervisors.map((s) => {
const supervisorsWithUuid = data.output.recommended_supervisors.map(
(s) => {
return { ...s, uuid: v4() } as ISupervisor;
});
},
);
updateChat(chat.uuid, {
helloMessage: data.recommendation.hello_message,
helloMessage: data.output.hello_message,
supervisors: supervisorsWithUuid,
});
return data;
Expand Down Expand Up @@ -95,7 +94,9 @@ export function Recommendation({
<span className="w-4/5">
Wystąpił błąd przy pobieraniu rekomendacji.
<br />
Spróbuj ponownie później.
Spróbuj ponownie później. Treść błędu:
<br />
<span className="text-sm">{error.message}</span>
</span>
</div>
) : (
Expand Down
25 changes: 22 additions & 3 deletions src/components/supervisor.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import { Star } from "lucide-react";
import { FileText, GraduationCap, Star } from "lucide-react";

import { Button } from "@/components/ui/button";
import { useSupervisors } from "@/hooks/use-supervisors";
Expand All @@ -14,7 +14,7 @@ import {
} from "./ui/accordion";

export function Supervisor({
supervisor: { uuid, faculty, name, papers },
supervisor: { uuid, faculty, name, papers, theses },
chatUuid,
prompt,
}: {
Expand Down Expand Up @@ -42,6 +42,7 @@ export function Supervisor({
faculty,
name,
papers,
theses,
prompt,
chatUuid,
createdAt: new Date(),
Expand All @@ -59,12 +60,30 @@ export function Supervisor({
<AccordionTrigger className="py-0">
<div className="flex flex-col gap-1">
<p className="text-xl font-bold">{name}</p>
<p>{faculties[faculty] || "Nieznany wydział"}</p>
<p>{faculties[faculty] || faculty}</p>
</div>
</AccordionTrigger>
<AccordionContent className="space-y-6 pb-2 pt-4">
{papers.map(({ title, description }) => (
<div key={title} className="flex max-w-lg flex-col gap-1">
<div
className="flex items-center gap-1 text-sm text-color-primary"
title={`${name} jest jednym z autorów tej pracy`}
>
<FileText className="size-4" /> Praca naukowa
</div>
<p className="text-lg font-medium">{title}</p>
<p>{description}</p>
</div>
))}
{theses.map(({ title, description }) => (
<div key={title} className="flex max-w-lg flex-col gap-1">
<div
className="flex items-center gap-1 text-sm text-color-primary"
title={`${name} był/a promotorem tej pracy`}
>
<GraduationCap className="size-4" /> Promotor
</div>
<p className="text-lg font-medium">{title}</p>
<p>{description}</p>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/lib/mock-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ export async function mockFetch(
} as Response;

resolve(response);
}, 10_000);
}, 3000);
});
}
99 changes: 70 additions & 29 deletions src/lib/mock-response.json
Original file line number Diff line number Diff line change
@@ -1,63 +1,104 @@
{
"faculty": "Faculty of Information and Communication Technology",
"question": "Web development",
"retrieved_docs": [],
"recommendation": {
"hello_message": "Here are some suitable supervisors for your thesis on web development at Politechnika Wrocławska:",
"output": {
"hello_message": "[MOCK] Oto rekomendacje promotorów związanych z uczeniem maszynowym na Politechnice Wrocławskiej:",
"recommended_supervisors": [
{
"name": "dr inż. Jakub Długosz",
"faculty": "Faculty of Information and Communication Technology",
"name": "Dr. Anna Kowalska",
"faculty": "Wydział Informatyki",
"papers": [
{
"title": "Web services performance testing with the use of CMS and CDN systems",
"description": "performance europe cms focuses displayed metrics heavy stability potential generally contributing key better demonstrated websites interestingly point vercel 10 layout examining presents pages user united states also generator underlying making suggest hosting website site anomaly spanned robustness across shift contributes insights observations understand owners disparities analysis informed thesis byte uncovers platforms collected exhibited indicating regions regional three events differences results however domain decisions study occurrences future may groundwork research variations architecture choosing comprehensive cloudflare data popular created jamstack subtle index lays speed need time assist service first comparable static experience cls approximately two valuable factors cumulative outperforming using basic complex ttfb asia lighthouse findings platform dynamics"
"title": "Zastosowanie algorytmów uczenia maszynowego w analizie danych medycznych",
"description": "Badanie zastosowania algorytmów ML w analizie danych z badań medycznych, skupiające się na poprawie dokładności diagnoz."
},
{
"title": "Optymalizacja modeli uczenia maszynowego",
"description": "Praca nad technikami optymalizacji modeli ML, aby zwiększyć ich wydajność i dokładność w różnych zastosowaniach."
}
],
"theses": [
{
"title": "Uczenie maszynowe w systemach rekomendacyjnych",
"description": "Analiza zastosowania ML w systemach rekomendacyjnych, z przykładami implementacji i wynikami."
}
]
},
{
"name": "dr inż. Anna Lauks-Dutka",
"faculty": "Faculty of Information and Communication Technology",
"name": "Prof. Jan Nowak",
"faculty": "Wydział Elektroniki",
"papers": [
{
"title": "A web application supporting the work of tutors",
"description": "web document describes framework the~technologies chosen software functional interface non-functional discussed justifies selected tutors presented project application developed requirements potential process install django based responsive provides issue analysis description attractiveness support fragments creating relation work development aspects system implementation design selection increase user includes paths business"
"title": "Sieci neuronowe w rozpoznawaniu obrazów",
"description": "Badanie efektywności sieci neuronowych w zadaniach rozpoznawania obrazów, z zastosowaniem różnych architektur."
},
{
"title": "Web application supporting personnel management in projects",
"description": "problem incorporated skills optimal purpose ought furthermore offer management additionally type users weighted obtain paper five exact functionalities implemented tested project auction sense design assists successive result algorithms tries based one answer algorithm hungarian reasonable best matching assignment shortest time web maximum software relaxation cycle-cancelling implement application size basic solve still tasks network paths"
"title": "Algorytmy uczenia głębokiego w przetwarzaniu języka naturalnego",
"description": "Analiza zastosowania algorytmów głębokiego uczenia w NLP, z przykładami zastosowań w analizie tekstu."
}
],
"theses": [
{
"title": "Zastosowanie uczenia maszynowego w automatyzacji procesów",
"description": "Praca dotycząca wykorzystania ML do automatyzacji różnych procesów przemysłowych."
}
]
},
{
"name": "Dr. Piotr Wiśniewski",
"faculty": "Wydział Matematyki",
"papers": [
{
"title": "Statystyka i uczenie maszynowe: połączenie teorii i praktyki",
"description": "Zbadanie związku między statystyką a ML, z przykładami zastosowań w praktyce."
},
{
"title": "Using a voice assistant to communicate with a service analyzing data from the application for controlling the hydroponic systems",
"description": "easier skill version designed provided serverless hydroponics framework states used customer interface implemented source two technologies implement app make bsc application using cloud purpose access alexa 3.9 aws extension invoked thesis controlling assistant systems relays every python data modern task aspects system platform design voice involved measurements code ran time includes lambda"
"title": "Modelowanie predykcyjne z wykorzystaniem uczenia maszynowego",
"description": "Praca dotycząca technik modelowania predykcyjnego z użyciem ML, z przykładami zastosowań."
}
],
"theses": [
{
"title": "Uczenie maszynowe w analizie finansowej",
"description": "Analiza zastosowania ML w analizie danych finansowych, z przykładami implementacji."
}
]
},
{
"name": "dr inż. Marek Kopel",
"faculty": "Faculty of Information and Communication Technology",
"name": "Dr. Marta Zielińska",
"faculty": "Wydział Fizyki",
"papers": [
{
"title": "Responsive web design: testing usability of mobile web applications",
"description": "developing usability various small proportions prospective tests problem tools developed employed paradigms approach web patterns results great smartphones utilization devices sizes dynamically implemented using mobile different goal responsive thoroughly test formulated designing monitors applications two management screen users obtained inspections including application paper design number versions adapting techniques desktop conference recommendations ranging automated scientific rwd well large allows individual analysed orientations diverse experts"
"title": "Zastosowanie uczenia maszynowego w fizyce",
"description": "Badanie zastosowań ML w różnych dziedzinach fizyki, z przykładami konkretnych badań."
},
{
"title": "Automatic web-based user interface delivery for soa-based systems",
"description": "ontology-based flexible up-to-date web-based consequence usually sophisticated semi-automatically soa input output functionalities parameters today defines services methodologies authoring great corresponding interface systems implemented programmers service method enhanced building user software present based generation ontology character presented delivered oriented set paper design however automatic description interfaces need manually interactive designers paradigm implementation interoperable"
"title": "Algorytmy uczenia maszynowego w analizie danych eksperymentalnych",
"description": "Analiza zastosowania ML w analizie danych z eksperymentów fizycznych."
}
],
"theses": [
{
"title": "Uczenie maszynowe w badaniach materiałowych",
"description": "Zastosowanie ML w badaniach nad nowymi materiałami, z przykładami wyników."
}
]
},
{
"name": "dr inż. Sławomir Sambor",
"faculty": "Faculty of Information and Communication Technology",
"name": "Prof. Krzysztof Jankowski",
"faculty": "Wydział Automatyki",
"papers": [
{
"title": "Project of a logic analyzer based on the Nucleo STM32.",
"description": "develop main summary solutions functional beginning conducted end presented realized application project next process using purpose stm32 control analyzer thesis logic 8-channel development conclusions drew tests analyzers part microcontroller assumptions implementation design existing computer described market"
"title": "Inteligencja obliczeniowa w systemach automatyki",
"description": "Zastosowanie ML w automatyce, z przykładami zastosowań w systemach sterowania."
},
{
"title": "Design of a secure computer network with Wi-Fi access in a three-story office building.",
"description": "switch hiding moment port-security proper within used internet unauthorized outside someone ssid connection project terms provide create persons floor latest wi-fi access one encryption password three-storey company office communication router devices building located work cases wanted connectivity best connect wireless secure aim computer network ensure gateway mobile"
"title": "Optymalizacja procesów z użyciem algorytmów uczenia maszynowego",
"description": "Badanie technik optymalizacji procesów przemysłowych z użyciem ML."
}
],
"theses": [
{
"title": "Uczenie maszynowe w robotyce",
"description": "Analiza zastosowania ML w robotyce, z przykładami implementacji w systemach robotycznych."
}
]
}
Expand Down
25 changes: 3 additions & 22 deletions src/types/api-types.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,12 @@
import type { SupervisorResponse } from "./supervisor";

export interface RawApiRecommendation {
export interface RecommendationResponse {
output: {
faculty: string;
question: string;
retrieved_docs: string[];
prompt: string;
recommendation: Recommendation;
hello_message: string;
recommended_supervisors: SupervisorResponse[];
};
metadata: Metadata;
}

export interface Recommendation {
hello_message: string;
recommended_supervisors: SupervisorResponse[];
}

interface Metadata {
run_id: string;
feedback_tokens: string[];
}

export type RecommendationResponse = Omit<
RawApiRecommendation["output"],
"retrieved_docs" | "prompt" | "metadata"
>;

export interface RecommendationRequest {
input: {
question: string;
Expand Down
1 change: 1 addition & 0 deletions src/types/supervisor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ interface SupervisorResponse {
name: string;
faculty: string;
papers: Paper[];
theses: Paper[];
}

interface Supervisor extends SupervisorResponse {
Expand Down

0 comments on commit 549f123

Please sign in to comment.