NextJs 및 ExpressJs 앱에서 DeepSeek API를 통합하는 법
2025-02-13 05:16:18NextJs 및 ExpressJs 앱에 DeepSeek API 통합하기
최근 AI 기술의 발전은 IT 산업에 큰 혁신을 가져오고 있습니다. 이러한 AI 기술을 활용하여 여러분의 프로젝트에 가치를 더할 수 있는 방법 중 하나는 API를 통해 AI 기능을 통합하는 것입니다. 이번 포스트에서는 NextJs 및 ExpressJs 앱에 DeepSeek API를 통합하는 방법을 자세히 설명드리겠습니다.
프로젝트 소개
"Finance Tracker"라는 샘플 프로젝트를 통해 DeepSeek API를 활용하여 사용자의 금융 거래를 기록하고 관리할 수 있는 개인 회계 챗봇을 구축할 것입니다. 이 프로젝트의 프론트엔드는 NextJs로, 백엔드는 tRPC(Express 어댑터)와 Drizzle ORM을 사용하는 Postgres 데이터베이스로 구성되었습니다. Github Repository에서 프로젝트 확인하기
DeepSeek API 키 얻기
DeepSeek API는 OpenAI의 API보다 저렴하고 성능이 뛰어난 AI 모델로 주목받고 있습니다. 이러한 이유로 DeepSeek API는 많은 트래픽을 끌어모았고, 때문에 가동 중단 시간도 있었습니다. 따라서 OpenRouter를 사용하여 여러 AI 모델 중 하나로 전환할 수 있는 방법을 사용하겠습니다.
- OpenRouter는 다양한 AI 모델에 대해 접근을 허용하며, 공급자가 차단될 경우 다른 모델로 전환합니다.
API 통합 시작하기
DeepSeek API 키를 백엔드의 환경 변수 파일(backend/.env)에 추가하세요.
DEEPSEEK_API_KEY=your_deepseek_api_key
OpenAI SDK 설치하기
yarn add openai
AI 컨트롤러 생성
AI 회계 코드 작성은 src/modules/ai/ai.controller.ts 파일에서 진행합니다. 먼저 OpenAI 클라이언트를 초기화합니다.
export default class AiController {
private readonly openai: OpenAI;
constructor() {
this.openai = new OpenAI({
baseURL: "https://openrouter.ai/api/v1",
apiKey: process.env.DEEPSEEK_API_KEY,
});
}
}
AI 회계 인텔리전트 설계
사용자의 거래 데이터를 데이터베이스에서 가져와 AI 모델에게 제공합니다. AI 모델은 이러한 데이터를 바탕으로 사용자 쿼리에 응답하게 됩니다.
async accountant(req: Request, res: Response) {
try {
const { query } = req.body;
if (!query) {
return res.status(400).json({ error: "요청 쿼리가 필요합니다" });
}
const userId = req.user.id;
const data = await db
.select()
.from(transactions)
.where(eq(transactions.userId, userId));
if (data.length === 0) {
return res.status(400).json({ error: "거래 내역이 없습니다" });
}
const formattedTxns = data.map((txn) => ({
amount: txn.amount,
txnType: txn.txnType,
summary: txn.summary,
tag: txn.tag,
date: txn.createdAt,
}));
const prompt = `
개인 회계사입니다. 거래 내역이 포함된 정보를 바탕으로 사용자 쿼리에 대답해야 합니다.
거래 내역: ${JSON.stringify(formattedTxns)}
화폐: ₩ (KRW)
사용자 질문: ${query}
`;
const response = await this.openai.chat.completions.create({
model: "deepseek/deepseek-chat",
messages: [{ role: "user", content: prompt }],
stream: true,
});
res.writeHead(200, {
"Content-Type": "text/plain",
"transfer-encoding": "chunked",
});
for await (const chunk of response) {
if (chunk.choices[0].finish_reason === "stop") {
break;
}
res.write(chunk.choices[0].delta.content || "");
}
res.end();
} catch (error) {
console.error({ error });
if (!res.headersSent) {
res.status(500).json({ error: "내부 서버 오류" });
}
}
}
프론트엔드 UI 생성
이제 프론트엔드에서 개인 회계 챗봇 UI를 만들어 봅시다. src/components/modules/dashboard 디렉터리에 chat.tsx라는 파일을 생성하고, 사용자와 상호작용할 수 있는 채팅 상자를 구현합니다.
export default function Chat() {
const [conversation, setConversation] = useState<
{ role: string; content: string; }[]
>([
{
role: "assistant",
content: "안녕하세요, 오늘 어떻게 도와드릴까요?",
},
]);
const [liveResponse, setLiveResponse] = useState<string>("");
const [isThinking, setIsThinking] = useState<boolean>(false);
// 새로운 메시지가 추가될 때 자동으로 스크롤
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollIntoView({ behavior: "smooth" });
}
}, [conversation, liveResponse]);
return (
<Popover>
<PopoverTrigger className="absolute right-4 bottom-4" asChild>
<Button size={"icon"} className="rounded-full">
<BotMessageSquareIcon className="w-4 h-4" />
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-[500px] h-[600px] p-0 space-y-4">
<h1 className="text-xl font-bold text-center p-4 pb-0">
개인 회계사
</h1>
<hr />
<div className="pt-0 relative h-full">
<div className="flex flex-col gap-2 h-[calc(100%-150px)] overflow-y-auto px-4 pb-20">
{conversation.map((message, index) => (
<div
key={index}
className={cn("flex flex-row gap-2 items-start", {
"rounded-lg bg-muted p-2 ml-auto flex-row-reverse":
message.role === "user",
})}
>
// 메시지 내용
</div>
))}
</div>
</div>
</PopoverContent>
</Popover>
);
}
결론
DeepSeek API를 NextJs와 ExpressJs에 통합하여 개인 맞춤형 회계사 같은 챗봇을 개발하는 과정을 살펴보았습니다. 이러한 통합은 사용자 경험을 크게 향상시키고, 프로젝트에 AI를 활용한 혁신적인 기능을 더하는 좋은 방법입니다.
참고하면 도움 될만한 URL: