ChatOllama 통합
ChatOllama 통합
LangChain JavaScript로 ChatOllama 채팅 모델과 통합하는 방법을 안내할게요.
출처: 문서
본문
Ollama를 사용하면 Llama 3.1과 같은 오픈소스 대규모 언어 모델(LLM)을 로컬에서 실행할 수 있어요.
Ollama는 모델 가중치, 구성, 데이터를 단일 패키지로 묶고 Modelfile로 정의해요. GPU 사용을 포함한 설정과 구성 세부 사항을 최적화해 줘요.
이 가이드는 ChatOllama 채팅 모델을 시작하는 데 도움을 줘요. 모든 ChatOllama 기능과 구성에 대한 자세한 문서는 API 레퍼런스를 참고하세요.
개요
통합 세부 정보
Ollama는 다양한 기능을 가진 광범위한 모델을 사용할 수 있게 해줘요. 아래 세부 정보 표의 일부 필드는 Ollama가 제공하는 모델의 일부 하위 집합에만 적용돼요.
지원되는 모델과 모델 변형의 전체 목록은 Ollama 모델 라이브러리에서 태그로 검색해 확인하세요.
| 클래스 | 패키지 | Serializable | PY 지원 | Downloads | Version |
|---|---|---|---|---|---|
ChatOllama |
@langchain/ollama |
beta | ✅ |
모델 기능
아래 표 헤더의 링크에서 특정 기능을 사용하는 방법에 대한 가이드를 확인할 수 있어요.
| Tool calling | Structured output | Image input | Audio input | Video input | Token-level streaming | Token usage | Logprobs |
|---|---|---|---|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ |
설정
이 지침을 따라 로컬 Ollama 인스턴스를 설정하고 실행하세요. 그런 다음 @langchain/ollama 패키지를 다운로드하세요.
자격 증명
모델 호출의 자동 추적(tracing)을 원한다면 아래 주석을 해제해 LangSmith API 키를 설정할 수도 있어요:
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
설치
LangChain ChatOllama 통합은 @langchain/ollama 패키지에 있어요:
yarn add @langchain/ollama @langchain/core
pnpm add @langchain/ollama @langchain/core
인스턴스 생성
이제 모델 객체를 생성하고 채팅 완성을 생성할 수 있어요:
import { ChatOllama } from "@langchain/ollama"
const llm = new ChatOllama({
model: "llama3",
temperature: 0,
maxRetries: 2,
// other params...
})
호출
const aiMsg = await llm.invoke([
[
"system",
"You are a helpful assistant that translates English to French. Translate the user sentence.",
],
["human", "I love programming."],
])
aiMsg
AIMessage {
"content": "Je adore le programmation.\n\n(Note: \"programmation\" is the feminine form of the noun in French, but if you want to use the masculine form, it would be \"le programme\" instead.)",
"additional_kwargs": {},
"response_metadata": {
"model": "llama3",
"created_at": "2024-08-01T16:59:17.359302Z",
"done_reason": "stop",
"done": true,
"total_duration": 6399311167,
"load_duration": 5575776417,
"prompt_eval_count": 35,
"prompt_eval_duration": 110053000,
"eval_count": 43,
"eval_duration": 711744000
},
"tool_calls": [],
"invalid_tool_calls": [],
"usage_metadata": {
"input_tokens": 35,
"output_tokens": 43,
"total_tokens": 78
}
}
console.log(aiMsg.content)
Je adore le programmation.
(Note: "programmation" is the feminine form of the noun in French, but if you want to use the masculine form, it would be "le programme" instead.)
도구 (Tools)
Ollama는 이제 일부 사용 가능한 모델에 대해 네이티브 tool calling을 지원해요. 아래 예제는 Ollama 모델에서 도구를 호출하는 방법을 보여줘요.
import { tool } from "@langchain/core/tools";
import { ChatOllama } from "@langchain/ollama";
import * as z from "zod";
const weatherTool = tool((_) => "Da weather is weatherin", {
name: "get_current_weather",
description: "Get the current weather in a given location",
schema: z.object({
location: z.string().describe("The city and state, e.g. San Francisco, CA"),
}),
});
// Define the model
const llmForTool = new ChatOllama({
model: "llama3-groq-tool-use",
});
// Bind the tool to the model
const llmWithTools = llmForTool.bindTools([weatherTool]);
const resultFromTool = await llmWithTools.invoke(
"What's the weather like today in San Francisco? Ensure you use the 'get_current_weather' tool."
);
console.log(resultFromTool);
AIMessage {
"content": "",
"additional_kwargs": {},
"response_metadata": {
"model": "llama3-groq-tool-use",
"created_at": "2024-08-01T18:43:13.2181Z",
"done_reason": "stop",
"done": true,
"total_duration": 2311023875,
"load_duration": 1560670292,
"prompt_eval_count": 177,
"prompt_eval_duration": 263603000,
"eval_count": 30,
"eval_duration": 485582000
},
"tool_calls": [
{
"name": "get_current_weather",
"args": {
"location": "San Francisco, CA"
},
"id": "c7a9d590-99ad-42af-9996-41b90efcf827",
"type": "tool_call"
}
],
"invalid_tool_calls": [],
"usage_metadata": {
"input_tokens": 177,
"output_tokens": 30,
"total_tokens": 207
}
}
구조화된 출력 (Structured output)
Ollama는 모든 모델에 대해 구조화된 출력을 네이티브로 지원하며, .withStructuredOutput()을 호출해 모델이 특정 형식을 반환하도록 강제할 수 있어요.
import { ChatOllama } from "@langchain/ollama";
import { z } from "zod";
// Define the schema
const Country = z.object({
name: z.string(),
capital: z.string(),
languages: z.array(z.string()),
});
// Define the model
const llm = new ChatOllama({
model: "llama3.1",
temperature: 0,
});
// Pass the schema to enforce a specific output format
const structuredLlm = llm.withStructuredOutput(Country);
const result = await structuredLlm.invoke("Tell me about Canada.");
console.log(result);
{
name: 'Canada',
capital: 'Ottawa',
languages: [ 'English', 'French' ]
}
tool calling을 통해 구조화된 출력을 사용하려면 method: "functionCalling" 옵션을 전달하세요:
import { ChatOllama } from "@langchain/ollama";
import { z } from "zod";
// Define the schema
const Sentence = z.object({
nouns: z.array(z.string()),
});
// Define the model
const llm = new ChatOllama({
model: "llama3.1",
temperature: 0,
});
// Use structured output via tool calling
const structuredLlm = llm.withStructuredOutput(Sentence, { method: "functionCalling" });
const result = await structuredLlm.invoke("Extract all nouns: A cat named Luna who is 5 years old and loves playing with yarn. She has grey fur");
console.log(result);
{ nouns: [ 'cat', 'Luna', 'years', 'yarn', 'fur' ] }
멀티모달 모델
Ollama는 버전 0.1.15 이상에서 LLaVA와 같은 오픈소스 멀티모달 모델을 지원해요.
이미지를 메시지의 content 필드 일부로 멀티모달 지원 모델에 전달할 수 있어요:
import { ChatOllama } from "@langchain/ollama";
import { HumanMessage } from "@langchain/core/messages";
import * as fs from "node:fs/promises";
const imageData = await fs.readFile("../../../../../examples/hotdog.jpg");
const llmForMultiModal = new ChatOllama({
model: "llava",
baseUrl: "http://127.0.0.1:11434",
});
const multiModalRes = await llmForMultiModal.invoke([
new HumanMessage({
content: [
{
type: "text",
text: "What is in this image?",
},
{
type: "image_url",
image_url: `data:image/jpeg;base64,${imageData.toString("base64")}`,
},
],
}),
]);
console.log(multiModalRes);
AIMessage {
"content": " The image shows a hot dog in a bun, which appears to be a footlong. It has been cooked or grilled to the point where it's browned and possibly has some blackened edges, indicating it might be slightly overcooked. Accompanying the hot dog is a bun that looks toasted as well. There are visible char marks on both the hot dog and the bun, suggesting they have been cooked directly over a source of heat, such as a grill or broiler. The background is white, which puts the focus entirely on the hot dog and its bun. ",
"additional_kwargs": {},
"response_metadata": {
"model": "llava",
"created_at": "2024-08-01T17:25:02.169957Z",
"done_reason": "stop",
"done": true,
"total_duration": 5700249458,
"load_duration": 2543040666,
"prompt_eval_count": 1,
"prompt_eval_duration": 1032591000,
"eval_count": 127,
"eval_duration": 2114201000
},
"tool_calls": [],
"invalid_tool_calls": [],
"usage_metadata": {
"input_tokens": 1,
"output_tokens": 127,
"total_tokens": 128
}
}
API 레퍼런스
모든 ChatOllama 기능과 구성에 대한 자세한 문서는 API 레퍼런스를 참고하세요.
더 알아보기
- 이 문서를 MCP로 연결하면 Claude, VSCode 등에서 실시간 답변을 받을 수 있어요.
- GitHub에서 이 페이지 편집하기 또는 이슈 제출하기.