GoTrip) AI 여행 플래너

김민수·2024년 7월 24일
post-thumbnail

API route

import { NextResponse } from 'next/server';
import OpenAI from 'openai';

export const maxDuration = 60;
export const dynamic = 'force-dynamic';
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API,
});

const content = process.env.OPENAI_PLANNER_API;
function isError(error: unknown): error is Error {
  return error instanceof Error;
}

export async function POST(request: Request) {
  const { prompt } = await request.json();

  try {
    const response = await openai.chat.completions.create({
      model: 'gpt-4o',
      messages: [
        { role: 'system', content: content || '' },
        { role: 'user', content: prompt },
      ],
      temperature: 0.7,
      max_tokens: 4096,
    });

    if (
      response.choices &&
      response.choices[0] &&
      response.choices[0].message &&
      response.choices[0].message.content
    ) {
      return NextResponse.json({
        result: response.choices[0].message.content.trim(),
      });
    } else {
      return NextResponse.json(
        { error: 'Invalid response from OpenAI API' },
        { status: 500 },
      );
    }
  } catch (error) {
    if (isError(error)) {
      return NextResponse.json({ error: error.message }, { status: 500 });
    } else {
      return NextResponse.json(
        { error: 'An unknown error occurred' },
        { status: 500 },
      );
    }
  }
}

API 호출

  const handleSendClick = async () => {
    const { age, gender, budget, country } = inputValues;
    const { from, to } = dateRange || {};

    const newErrors: Errors = {};
    if (!age) newErrors.age = '나이 입력은 필수입니다.';
    if (!gender) newErrors.gender = '성별 입력은 필수입니다.';
    if (!budget) newErrors.budget = '예산 입력은 필수입니다.';
    if (!from || !to) newErrors.duration = '일정 선택은 필수입니다.';
    if (!country) newErrors.country = '나라 선택은 필수입니다.';

    setErrors(newErrors);

    if (Object.keys(newErrors).length > 0) {
      return;
    }
    setLoading(true);
    const duration = `${from?.toLocaleDateString()} - ${to?.toLocaleDateString()}`;
    const prompt = `나이: ${age}, 성별: ${gender}, 예산: ${budget}, 일정: ${duration}, 나라: ${country}`;

    try {
      const response = await fetch('/api/planner', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ prompt }),
      });

      const data = await response.json();
      setResult(data.result);
    } catch (error) {
      console.error('OpenAI API 요청 중 오류 발생:', error);
    } finally {
      setLoading(false);
    }
  };

0개의 댓글