Vercel에서 LlamaIndex.TS 활용하기: OpenAI와 Next.js 통합 가이드
2025-02-22 21:25:57Vercel에서 LlamaIndex.TS 활용하기
소개
LlamaIndex는 LLM과 데이터를 활용하기 위한 오픈 소스 프레임워크입니다. 기존에는 Python으로 작성되었으나, 이제는 JavaScript/TypeScript 환경에서도 사용이 가능합니다. 특히 Vercel을 통한 서버리스 배포가 가능합니다. 본 포스트에서는 Vercel 환경에서 LlamaIndex.TS를 활용하는 방법에 대해 자세히 알아보겠습니다.
기본 설정
먼저, Next.js 애플리케이션을 생성하고 Vercel에 프로젝트를 초기화합니다.
# Next.js 앱 초기화
npx create-next-app@latest .
# Vercel 프로젝트 초기화
vercel
Vercel에서 Node.js 버전 22를 사용하는 것이 권장됩니다. Nvm을 사용해 다음과 같이 설정할 수 있습니다.
nvm install 22
nvm use 22
이후, LlamaIndex 패키지를 설치합니다.
npm install llamaindex
TypeScript 설정
TypeScript의 tsconfig.json 파일을 확인해 moduleResolution 옵션이 bundler로 설정되어 있는지 검토하세요. 이렇게 해야 ESM, CJS, 조건부 익스포트 처리에 문제가 발생하지 않습니다.
{
"compilerOptions": {
"moduleResolution": "bundler"
}
}
next.config.mjs 설정
Next.js와의 통합을 위해 next.config.mjs 파일을 생성하고 llamaindex/next를 임포트합니다.
import withLlamaIndex from "llamaindex/next";
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default withLlamaIndex(nextConfig);
OpenAI와의 통합 예시
1. Helper 모듈 생성
lib/openai.ts 파일을 생성하여 OpenAI 호출을 위한 헬퍼 함수를 만듭니다.
import { OpenAI } from "@llamaindex/openai";
export async function getChatResponse(message: string) {
const llm = new OpenAI({ model: "gpt-4o-mini", temperature: 0.1 });
const response = await llm.chat({
messages: [{ content: message, role: "user" }],
});
return response.message.content;
}
2. 백엔드 API 엔드포인트
app/api/openai/route.ts에서 API 라우트를 설정하여 요청을 처리하고 헬퍼 함수를 호출하도록 합니다.
import { NextResponse } from 'next/server';
import { getChatResponse } from '@/lib/openai';
export async function POST(request: Request) {
try {
const { content } = await request.json();
const response = await getChatResponse(content);
return NextResponse.json({ response });
} catch (error) {
console.error('API Error:', error);
return NextResponse.json({ error: 'Error occurred' }, { status: 500 });
}
}
3. 프론트엔드 UI 컴포넌트
app/page.tsx에 간단한 테스트 UI를 작성합니다.
'use client';
import { useState } from 'react';
export default function Home() {
const [input, setInput] = useState('');
const [response, setResponse] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
const res = await fetch('/api/openai', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'chat', content: input }),
});
const data = await res.json();
setResponse(data.response);
} catch (error) {
console.error('Client Error:', error);
setResponse('An error occurred.');
}
};
return (
<div className="p-8">
<form onSubmit={handleSubmit}>
<textarea
value={input}
onChange={(e) => setInput(e.target.value)}
className="w-full p-2 border rounded"
/>
<button
type="submit"
className="mt-2 px-4 py-2 bg-blue-500 text-white rounded"
>
Submit
</button>
</form>
{response && (
<div className="mt-4 p-4 bg-gray-100 rounded">
{response}
</div>
)}
</div>
);
}
4. 환경 변수 설정
로컬 환경의 .env.local 파일에 OpenAI API 키를 추가합니다.
OPENAI_API_KEY=sk-xxxx...
또한, Vercel 대시보드의 환경 변수 설정에서도 동일한 키를 추가하여 배포된 함수에서 접근 가능하도록 합니다.
5. 로컬 테스트 및 배포
로컬 서버에서 실행하여 확인합니다.
npm run dev
모든 것이 정상이라면 Vercel에 배포합니다.
vercel deploy
Vercel AI SDK 사용 예시
1. SDK 설치
Vercel AI SDK를 설치합니다.
npm install ai
2. API 라우트 생성
LlamaIndex 어댑터를 사용하는 간단한 API 라우트를 만듭니다.
// app/api/aisdk/route.ts
import { OpenAI, SimpleChatEngine } from 'llamaindex';
import { LlamaIndexAdapter } from 'ai';
export const maxDuration = 60; // optional, define your own constants
export async function POST(req: Request) {
console.log('ai sdk route');
const { prompt } = await req.json();
const llm = new OpenAI({ model: 'gpt-4o-mini' });
const chatEngine = new SimpleChatEngine({ llm });
const stream = await chatEngine.chat({
message: prompt,
stream: true,
});
return LlamaIndexAdapter.toDataStreamResponse(stream);
}
3. useCompletion을 사용하는 프론트엔드
useCompletion 훅을 사용하여 프론트엔드에서 스트리밍 응답을 처리합니다.
'use client';
import { useCompletion } from 'ai/react';
export default function Home() {
const { completion, input, handleInputChange, handleSubmit } = useCompletion({
api: '/api/aisdk',
});
return (
<div className="p-8">
<form onSubmit={handleSubmit}>
<textarea
value={input}
onChange={handleInputChange}
className="w-full p-2 border rounded"
/>
<button
type="submit"
className="mt-2 px-4 py-2 bg-blue-500 text-white rounded"
>
Submit
</button>
</form>
{completion && (
<div className="mt-4 p-4 bg-gray-100 rounded">
{completion}
</div>
)}
</div>
);
}
결론
Vercel에서 LlamaIndex.TS를 활용하는 것은 다양한 가능성을 열어줍니다. OpenAI와의 통합을 통해 서버리스 환경에서 효과적인 LLM 활용이 가능하며, Vercel의 다양한 도구와의 시너지를 기대할 수 있습니다. 이 가이드를 통해 자신의 프로젝트에 LlamaIndex.TS를 통합해 보세요.