최근 인공지능(AI)과 대규모 언어 모델(LLM)이 대화의 중심을 차지하고 있다는 사실은 부인할 수 없습니다. 거의 매주 새로운 모델이 출시되고, 새로운 통합 기능(예: AI 에이전트 및 연산자)이 개발되고 있습니다. 이처럼 흥미진진한 흐름에 동참하지 않는 것은 어리석은 일입니다.
이 글에서는 Ollama를 Next.js와 통합하여 LLM(Llama Language Model) 기반 애플리케이션을 구축하는 방법을 살펴보겠습니다. Llama, DeepSeek, Mistral과 같은 오픈소스 LLM을 다운로드하고 상호 작용하는 방법, 그리고 ollama.js를 사용하여 Next.js에서 메시지를 보내고 LLM 응답을 처리하는 방법을 다룹니다. 최종 애플리케이션은 아래 이미지와 같습니다.
필수 조건
이 내용을 따라하려면 Next.js 에 대한 기본적인 이해 와 LLM이 내부적으로 어떻게 작동하는지에 대한 이해가 필요합니다.
올라마는 무엇인가요?
Ollama는 Michael Chiang과 Jeffrey Morgan이 LLM(Learning Modeling Model)을 다른 애플리케이션과 통합하는 과정을 간소화하기 위해 개발한 오픈 소스 프레임워크입니다. Ollama 자체는 LLM이 아니며, LLM을 다운로드하고, 상호 작용하고, 사용자 지정 모델을 생성할 수 있도록 지원합니다. 또한, 다운로드하거나 사용자 지정한 LLM을 다른 애플리케이션에 통합할 수 있도록 사전 구성된 API 엔드포인트를 제공합니다.
또한 Ollama를 Llama(철자 "O"가 없는)와 혼동해서는 안 된다는 점을 알아두세요. Llama는 Meta AI에서 개발한 오픈 소스 LLM입니다. 반면 Ollama는 다양한 LLM과의 통합을 지원하는 독립적인 오픈 소스 도구입니다. 이제 이 점을 명확히 했으니, 실제 통합 사례를 살펴보겠습니다.
올라마 설정하기
시작하려면 Ollama 공식 웹사이트에서 다운로드하세요. 다른 Unix/Linux 배포판을 사용하는 경우 다음 명령어를 실행하여 다운로드할 수도 있습니다.
curl -fsSL https://ollama.com/install.sh | sh
Ollama를 성공적으로 다운로드하고 설치했으면 다음 명령어를 실행하여 터미널/명령줄에서 실행 가능한지 확인하십시오.
ollama -v
모든 것이 순조롭게 진행되었다면 콘솔에 버전 번호가 출력될 것입니다. 이제 첫 번째 모델을 설치하고 사용해 보겠습니다.
모델을 가져와 실행하세요
앞서 언급했듯이 Ollama는 DeepSeek, Llama, Mistral, Qwen, Phi를 포함한 여러 오픈 소스 모델에 대한 액세스를 제공합니다. 지원되는 모델 목록은 여기에서 확인할 수 있습니다 .
모델 목록에서 Meta AI의 Llama 3.2는 인상적인 벤치마크 성능을 자랑하는 소형 모델로 현재 눈에 띕니다. 이 모델은 10억 파라미터(1.3GB)와 30억 파라미터(2GB) 두 가지 버전으로 제공됩니다. 이 튜토리얼에서는 크기가 작아 다루기 쉬운 Llama 3.2 10억 파라미터 모델을 사용하겠습니다. 진행하려면 다음 명령을 실행하여 모델을 다운로드하세요.
ollama run llama3.2:1b
이 명령어를 실행하면 Meta 레지스트리에서 Llama 3.2(10억 개 매개변수) 모델이 다운로드됩니다. 다운로드가 완료되면 모델이 실행되고, 아래 스크린샷처럼 바로 모델과 대화를 시작할 수 있습니다.
터미널에서 LLM과 직접 상호 작용하는 데 시간을 충분히 투자해 보세요. 준비가 되면 Next.js 애플리케이션에 LLM을 통합하는 방법을 살펴보겠습니다.
Ollama.js를 사용하여 Next.js의 LLM과 상호 작용하세요.
Ollama는 다운로드한 모델과 상호 작용할 수 있는 REST API 엔드포인트를 제공합니다. 데스크톱 앱이 실행되면, 해당 엔드포인트가 노출되며 http://localhost:11434/api, 이 엔드포인트를 통해 사용자 지정 HTTP 요청을 보내 상호 작용을 수행할 수 있습니다.
예를 들어, "퇴마란 무엇인가?"라는 질문에 대한 답을 생성하려면 /api/generate아래와 같이 원하는 모델과 질문을 지정하여 엔드포인트 로 POST 요청을 보낼 수 있습니다 .
curl http://localhost:11434/api/generate -d '{
"model": "llama3.2",
"prompt": "What is Exorcism?"
}'
그러면 응답 객체가 명령줄이나 터미널에 실시간으로 스트리밍되는 것을 볼 수 있습니다.
이 과정을 간소화하기 위해 Ollama 팀은 이러한 엔드포인트를 참조하고 다양한 작업을 수행하는 여러 메서드가 사전 구성된 JavaScript 라이브러리( ollama-js )를 개발했습니다. 우리는 애플리케이션에서 이 라이브러리를 활용할 것입니다.
계속 진행하려면 다음 명령을 실행하여 새 Next.js 앱을 생성하세요.
npx create-next-app next-ollama
설치 과정에서 Tailwind CSS와 pages/router를 선택하여 이 튜토리얼과의 일관성을 유지하십시오. 다른 모든 구성 옵션은 원하는 대로 사용자 지정할 수 있습니다.
새로운 Next.js 앱이 성공적으로 생성되면 프로젝트 디렉토리로 이동하여 다음 명령어를 실행하여 ollama-js를 설치하세요.
cd next-ollama
npm install ollama
다음으로, 앞서 설치한 LLM과 상호 작용할 수 있는 간단한 채팅 인터페이스를 만들어 보겠습니다. 기본 pages/index.js파일을 열고 다음 코드로 내용을 바꾸세요.
import { useState } from "react";
const Index = () => {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
const userMessage = { role: "user", content: input };
setMessages((prevMessages) => [...prevMessages, userMessage]);
setInput("");
/* ====
⚠️ Main logic to be added later
==== */
};
return (
<div className="max-w-2xl mx-auto p-4">
<div className="bg-white min-h-[400px] p-4 mb-4 rounded-xl border-2 border-gray-500 overflow-y-auto">
{messages.map((message, index) => (
<div
key={index}
className={`mb-4 ${
message.role === "user" ? "text-right" : "text-left"
}`}
>
<div
className={`inline-block p-3 rounded-2xl max-w-[80%] ${
message.role === "user"
? "bg-blue-600 text-white"
: "bg-gray-100 text-gray-800"
}`}
>
{message.content}
</div>
</div>
))}
{isLoading && (
<div className="text-left">
<div className="inline-block p-3 rounded-2xl bg-gray-100 text-gray-400">
Thinking...
</div>
</div>
)}
</div>
<form onSubmit={handleSubmit} className="flex gap-3">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
className="flex-1 p-3 rounded-xl border-2 border-gray-500"
placeholder="Type your message..."
/>
<button
type="submit"
className="bg-blue-600 text-white px-6 py-3 rounded-xl hover:bg-blue-700 transition-colors font-medium"
>
Send
</button>
</form>
</div>
);
};
export default Index;
위 코드는 메시지를 보내고 답장을 받을 수 있는 기본적인 채팅 인터페이스를 생성합니다. 또한 handleSubmit()현재는 별다른 기능을 하지 않는 함수도 포함되어 있는데, 이 함수에 Ollama를 사용하여 메시지를 처리하는 로직을 추가할 것입니다.
다음 명령을 실행하여 애플리케이션을 시작하세요.
npm run dev
그러면 아래 이미지와 유사한 채팅 인터페이스가 표시됩니다.
이제 Ollama를 통해 Llama 3.2로 메시지를 보내고 응답을 처리하는 API 엔드포인트를 만들어 보겠습니다. 이를 위해 기본 pages/api/디렉터리 안에 chat.js 파일을 새로 만들고 다음 코드를 붙여넣으세요.
import ollama from "ollama";
export default async function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ error: "Method not allowed" });
}
try {
const { message } = req.body;
const response = await ollama.chat({
model: "llama3.2",
messages: [{ role: "user", content: message }],
});
return res.status(200).json({ message: response.message.content });
} catch (error) {
console.error("Ollama API error:", error);
return res.status(500).json({ error: "Failed to get response from LLM" });
}
}
여기서는 Ollama를 임포트하고 요청 본문에 메시지를 포함하는 POST 요청을 허용하는 Next.js API 엔드포인트를 생성했습니다. 다음으로, .chat()이전에 설치한 LLM 모델(llama3.2)을 지정하고 수신된 메시지를 요청 객체의 일부로 전달하여 Ollama의 메서드를 호출했습니다.
통합을 완료하기 위해 새로 생성된 엔드포인트와 통신하도록 메인 채팅 인터페이스를 업데이트해 보겠습니다. pages/index.js파일을 열고 기존 handleSubmit()함수를 아래 코드로 교체하세요.
const handleSubmit = async (e) => {
e.preventDefault();
if (!input.trim()) return;
const userMessage = { role: "user", content: input };
setMessages((prevMessages) => [...prevMessages, userMessage]);
setInput("");
setIsLoading(true);
try {
const response = await fetch("/api/chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ message: input }),
});
if (!response.ok) {
throw new Error("Failed to get response");
}
const data = await response.json();
const aiMessage = {
role: "assistant",
content: data.message,
};
setMessages((prevMessages) => [...prevMessages, aiMessage]);
} catch (error) {
console.error("Error:", error);
const errorMessage = {
role: "assistant",
content: "Sorry, I encountered an error while processing your request.",
};
setMessages((prevMessages) => [...prevMessages, errorMessage]);
} finally {
setIsLoading(false);
}
};
이 단계에서는 파일이 여기에pages/index.js 제공된 파일과 일치해야 합니다 . 마지막으로 다음 명령을 실행하여 앱을 시작하세요.
npm run dev
콘솔에 표시된 URL(일반적으로 http://localhost:3000/ )로 이동하면 아래 이미지와 같이 Next.js 앱에서 Llama 3.2 LLM과 직접 채팅할 수 있습니다.
이제 완료되었습니다! Next.js 애플리케이션에서 로컬에 다운로드한 Llama 3.2 버전을 직접 사용할 수 있습니다. 다른 오픈 소스 모델도 가져와서 상호 작용할 수 있습니다.
결론
이 튜토리얼에서는 Ollama를 사용하여 오픈 소스 대규모 언어 모델(LLM)을 설치하고 다운로드하는 방법과 ollama-js 라이브러리를 사용하여 이러한 LLM을 Next.js 애플리케이션에 통합하는 방법을 다뤘습니다. 이 튜토리얼에서 사용된 전체 코드는 이 GitHub 저장소 에서 확인할 수 있습니다 .
다음 후속 기사에서는 최종 계산된 응답을 기다리지 않고 실시간으로 응답을 스트리밍하고 표시하는 방법을 살펴보겠습니다. 또한 LLM이 이전 대화를 기억하도록 하는 방법과 다른 ollama-js 메서드 및 커뮤니티 통합 기능에 대해서도 다룰 예정입니다. 그동안 여러분이 직접 만든 LLM 친구와 즐겁게 대화해 보세요!
읽어주셔서 감사합니다!
There’s no ignoring how AI and and large language models (LLMs) have dominated conversations lately. Nearly every week, new models are released, and new integrations (e.g AI agents and operators) are developed. It’s crazy not to want to jump on this exciting train.
In this article, we’ll explore how to integrate Ollama with Next.js to build LLM-powered applications. We’ll cover how to download and interact with open-source LLMs (such as Llama, DeepSeek, and Mistral), as well as how to send messages and process LLM responses in Next.js using ollama.js. Our final application will look like the image shown below.
Prerequisite
To follow along, you should have a basic understanding of Next.js and how LLMs work behind the scenes.
What is Ollama?
Ollama is an open-source framework founded by Michael Chiang and Jeffrey Morgan to simplify LLM integration with other applications. Ollama itself is not an LLM; instead, it allows you to download LLMs, interact with them, and create custom models. It also provides pre-configured API endpoints with which you can integrate downloaded or customized LLMs into other applications.
It’s also worth mentioning that Ollama should not be confused with Llama (without the "O"). Llama is an open-source LLM developed by Meta AI. In contrast, Ollama is an independent open-source tool that enables integration with various LLMs. With that clarified, let’s explore these integrations in practice.
Setting up ollama
To get started, download Ollama from its official website. If you’re using other Unix/Linux distro, you can also download it by running the following command.
curl -fsSL https://ollama.com/install.sh | sh
Once you’ve successfully downloaded and installed Ollama, run the following command to verify that it is now executable on your terminal/command line.
ollama -v
If everything went well, you should see the version number printed in your console. Next, let’s install and interact with our first model.
Pull and run a model
As mentioned previously, Ollama provides access to multiple open-source models, including DeepSeek, Llama, Mistral, Qwen, and Phi. You can also view the list of supported models here.
From the model list, Llama 3.2 (by Meta AI) presently stands out as a small-sized model with impressive benchmark stats. It is available in two variants: 1B parameters (1.3GB) and 3B parameters (2GB). For this tutorial, we’ll use the Llama 3.2 1B model, as its smaller size makes it more manageable. To proceed, download the model by running:
ollama run llama3.2:1b
This command will pull the Llama 3.2 (1B parameters) model from Meta’s registry. Once the download is complete, the model will launch, and you can start chatting with it right away, as shown in the screenshot below.
Feel free to spend some time interacting with the LLM directly from your terminal. Once you're ready, let’s dive into bringing it into a Next.js application.
Interact with LLMs in Next.js with Ollama.js
Ollama provides REST API endpoints that allow you to interact with downloaded models. Once the desktop app is running, it exposes an endpoint at http://localhost:11434/api, where you can send custom HTTP requests to perform interactions.
For example, to generate an answer to the question "What is Exorcism?", we can send a POST request to the /api/generate endpoint, specifying our preferred model and question, as shown below:
curl http://localhost:11434/api/generate -d '{
"model": "llama3.2",
"prompt": "What is Exorcism?"
}'
You should then see the response objects streamed to your command line or terminal in real-time:
To simplify the process, the Ollama team created a JavaScript library (ollama-js) that comes pre-configured with various methods for referencing these endpoints and performing different tasks. We’ll leverage this library in our application.
To proceed, create a new Next.js app by running the following command:
npx create-next-app next-ollama
During the installation process, select Tailwind CSS and the pages/ router to ensure consistency with this tutorial. All other configuration options can be customized to your preference.
Once your new Next.js app is successfully created, navigate to the project directory and install ollama-js by running the following commands:
cd next-ollama
npm install ollama
Next, let’s create a simple chat interface to interact with the LLM we installed earlier. Open the default pages/index.js file and replace its contents with the following code:
import { useState } from "react";
const Index = () => {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
const userMessage = { role: "user", content: input };
setMessages((prevMessages) => [...prevMessages, userMessage]);
setInput("");
/* ====
⚠️ Main logic to be added later
==== */
};
return (
<div className="max-w-2xl mx-auto p-4">
<div className="bg-white min-h-[400px] p-4 mb-4 rounded-xl border-2 border-gray-500 overflow-y-auto">
{messages.map((message, index) => (
<div
key={index}
className={`mb-4 ${
message.role === "user" ? "text-right" : "text-left"
}`}
>
<div
className={`inline-block p-3 rounded-2xl max-w-[80%] ${
message.role === "user"
? "bg-blue-600 text-white"
: "bg-gray-100 text-gray-800"
}`}
>
{message.content}
</div>
</div>
))}
{isLoading && (
<div className="text-left">
<div className="inline-block p-3 rounded-2xl bg-gray-100 text-gray-400">
Thinking...
</div>
</div>
)}
</div>
<form onSubmit={handleSubmit} className="flex gap-3">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
className="flex-1 p-3 rounded-xl border-2 border-gray-500"
placeholder="Type your message..."
/>
<button
type="submit"
className="bg-blue-600 text-white px-6 py-3 rounded-xl hover:bg-blue-700 transition-colors font-medium"
>
Send
</button>
</form>
</div>
);
};
export default Index;
The code above creates a basic chat interface that allows us to send messages and receive responses. It also includes a handleSubmit() function, which doesn’t do much at this point, but this is where we’ll add the logic to process our messages with Ollama.
Start your application by running:
npm run dev
You should then see a chat interface similar to the image below.
Now, let’s create an API endpoint to send our message to Llama 3.2 via Ollama and process the response. To do this, create a new chat.js file inside the default pages/api/ directory and paste the following code into it.
import ollama from "ollama";
export default async function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ error: "Method not allowed" });
}
try {
const { message } = req.body;
const response = await ollama.chat({
model: "llama3.2",
messages: [{ role: "user", content: message }],
});
return res.status(200).json({ message: response.message.content });
} catch (error) {
console.error("Ollama API error:", error);
return res.status(500).json({ error: "Failed to get response from LLM" });
}
}
Here, we imported Ollama and created a Next.js API endpoint that accepts POST requests with a message in the request body. Next, we called Ollama’s .chat() method, specifying the LLM model we installed earlier (llama3.2) and passing the received message as part of the request object.
To complete our integration, let’s update the main chat interface to communicate with the newly created endpoint. Open the pages/index.js file and replace the existing handleSubmit() function with the code below.
const handleSubmit = async (e) => {
e.preventDefault();
if (!input.trim()) return;
const userMessage = { role: "user", content: input };
setMessages((prevMessages) => [...prevMessages, userMessage]);
setInput("");
setIsLoading(true);
try {
const response = await fetch("/api/chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ message: input }),
});
if (!response.ok) {
throw new Error("Failed to get response");
}
const data = await response.json();
const aiMessage = {
role: "assistant",
content: data.message,
};
setMessages((prevMessages) => [...prevMessages, aiMessage]);
} catch (error) {
console.error("Error:", error);
const errorMessage = {
role: "assistant",
content: "Sorry, I encountered an error while processing your request.",
};
setMessages((prevMessages) => [...prevMessages, errorMessage]);
} finally {
setIsLoading(false);
}
};
At this stage, your pages/index.js file should match the one provided here. Finally, start your app by running:
npm run dev
Go to the URL displayed in your console (typically http://localhost:3000/), and you should now be able to chat with the Llama 3.2 LLM directly from your Next.js app, as shown in the image below.
And we’re done! You can now start interacting with a locally downloaded version of Llama 3.2 directly from your Next.js application. You can also pull other open-source models and interact with them.
Conclusion
In this tutorial, we covered how to install and download open-source large language models (LLMs) with Ollama, as well as how to use the ollama-js library to integrate these LLMs into a Next.js application. You can find the complete code used in this tutorial in this GitHub repository.
In an upcoming follow-up article, we’ll explore how to stream responses and display them in real-time instead of waiting for the final computed response. We’ll also cover how to make the LLM remember our previous conversations, along with other ollama-js methods and community integrations. In the meantime, enjoy chatting with your custom-built LLM friend!
Thanks for reading!
[출처] https://dev.to/asaoluelijah/how-to-integrate-ollama-in-nextjs-5aa7






