Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Node.jsでllama_2_.pdf
Search
Optimisuke
February 21, 2024
Technology
240
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Node.jsでllama_2_.pdf
kansai.ts #5 2024/02/21 で発表したスライドです。
Optimisuke
February 21, 2024
More Decks by Optimisuke
See All by Optimisuke
量子コンピュータ勉強会#1
optimisuke
0
48
LangChainやるならPythonよりTypeScriptの方がいんじゃね?
optimisuke
1
1.5k
オンオフの切り替え
optimisuke
0
73
Other Decks in Technology
See All in Technology
幾何アルゴリズムで なめらかなピン操作を / iOSDC Japan 2026 / smoothpin
kazumanagano
0
300
ASTを使って影響範囲を特定する
nealle
0
180
Snowflakeで実現する全社横断の顧客の声(VOC)分析・活用基盤@Snowflake World Tour Tokyo 2026
yuto16
0
200
深夜のクラウド懺悔室 1:29:300 or 1:0:0
kazzpapa3
1
240
アプリログインとWeb認証基盤をつなぐ ASWebAuthenticationSession 作法
shimastripe
1
280
多層防御と最⼩権限で実現する、安全なAIエージェント設計パターン
lycorptech_jp
PRO
1
280
アプリをもっと"iOSアプリっぽく"する小さな工夫 / Small Touches That Make Your App Feel More Like an iOS App
matsuji
1
760
20260906 「AWS運用入門」著者が教える、運用業務への生成AI活用入門
masaruogura
0
260
Screen Lens - 今見てる画面を翻訳する
komagata
0
260
なぜJMBC(Japan MCP Business Community)? MCPってどう活用できるの?
cdataj
0
110
10Xに技術的負債をもたらした「2つの境界の歪み」その構造と解消への営み
10xinc
0
690
Oracle Cloud Infrastructure IaaS 新機能アップデート 2026/6 - 2026/8
oracle4engineer
PRO
0
190
Featured
See All Featured
sira's awesome portfolio website redesign presentation
elsirapls
0
410
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
49
3.6k
The Cult of Friendly URLs
andyhume
79
7k
Designing Experiences People Love
moore
143
24k
Claude Code どこまでも/ Claude Code Everywhere
nwiizo
67
58k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
3k
Imperfection Machines: The Place of Print at Facebook
scottboms
270
14k
コードの90%をAIが書く世界で何が待っているのか / What awaits us in a world where 90% of the code is written by AI
rkaga
63
46k
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
49
10k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
123
22k
Conquering PDFs: document understanding beyond plain text
inesmontani
PRO
4
3k
HU Berlin: Industrial-Strength Natural Language Processing with spaCy and Prodigy
inesmontani
PRO
0
700
Transcript
Node.jsでllama 2🦙
はじめに ローカルでもLarge Language Models (LLM) を動かしてみたい MetaのLlama 2は色々できるらしい Pythonでも良いけど、TypeScriptでもやり たい
generated by chatgpt
Llama 2 MetaのLlama 2は、研究用途と商業用途 の両方に対応したオープンソースの大規 模言語モデル いろんなライブラリ・サービスがあってエコ システムがいい感じ rinna、ELYZA、stability.ai による日本語モ
デルも公開されている https://llama.meta.com/ generated by chatgpt
llama.cpp LlamaをC/C++で実装したもの。Apple silicon のGPUにも対応している。 https://github.com/ggerganov/llama.cpp?tab=readme-ov-file
node-llama-cpp Node.jsでllama.cppを動かすためのライブラリ Node-APIを使ってllama.cppを呼び出している Node-APIはネイティブアドオンの作成を可能にす るNode.jsのAPI。ネイティブアドオンとは、CやC++ などのコンパイル言語で書かれ、Node.jsの JavaScriptランタイムと統合されるモジュールのこ と。 https://github.com/withcatai/node-llama-cpp https://nodejs.org/api/n-api.html
🦜🔗 LangChain.js LangChainは、大規模言語モデルを活用し たアプリケーションの構築を支援するフレー ムワーク LangChain.jsはJavaScript/TypeScript版 (Python版がメイン) kansai.ts #4で話した https://www.langchain.com/
https://github.com/langchain-ai/langchainjs https://speakerdeck.com/optimisuke/langchainyarunarapythonyoritypescriptnofang-gainziyane
試してみた generated by chatgpt
node-llama-cpp 試してみた import { fileURLToPath } from "url"; import path
from "path"; import { LlamaModel, LlamaContext, LlamaChatSession } from "node-llama-cpp"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const model = new LlamaModel({modelPath: path.join(__dirname, "models", "ELYZA-japanese-Llama-2-7b-fast-instruct-q4_K_M.gguf")}); const context = new LlamaContext({ model }); const session = new LlamaChatSession({ context }); const q1 = "元気?"; console.log("User: " + q1); const a1 = await session.prompt(q1); console.log("AI: " + a1);
LangChain.js 試してみた import { LlamaCpp } from "@langchain/community/llms/llama_cpp"; const llamaPath
= "/Users/hoge/hello-node-llama-cpp/models/ELYZA-japanese-Llama-2-7b-fast-instru ct-q4_K_M.gguf"; const model = new LlamaCpp({ modelPath: llamaPath }); const question = "ラマって何?"; console.log(`User: ${question}`); const response = await model.invoke(question); console.log(`AI : ${response}`);
LangChain.js 試してみた import { ChatLlamaCpp } from "@langchain/community/chat_models/llama_cpp"; const llamaPath
= "/Users/hoge/hello-node-llama-cpp/models/ELYZA-japanese-Llama-2-7b-fast-instru ct-q4_K_M.gguf"; const model = new ChatLlamaCpp({ modelPath: llamaPath, temperature: 0.7 }); const stream = await model.stream("ラマって何?"); for await (const chunk of stream) { console.log(chunk.content); }
コードを見てみた generated by chatgpt
node-llama-cppのコードを見てみた class LLAMAModel : public Napi::ObjectWrap<LLAMAModel> { public: llama_model_params model_params;
llama_model* model; LLAMAModel(const Napi::CallbackInfo& info) : Napi::ObjectWrap<LLAMAModel>(info) { model_params = llama_model_default_params(); // Get the model path std::string modelPath = info[0].As<Napi::String>().Utf8Value(); llama_backend_init(false); model = llama_load_model_from_file(modelPath.c_str(), model_params); } };
node-llama-cppのコードを見てみた execute_process(COMMAND node -p "require('node-addon-api').include.slice(1,-1)" WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} OUTPUT_VARIABLE NODE_ADDON_API_DIR OUTPUT_STRIP_TRAILING_WHITESPACE)
include_directories(${NODE_ADDON_API_DIR} ${CMAKE_JS_INC}) include_directories("llama.cpp") file(GLOB SOURCE_FILES "addon.cpp") target_link_libraries(${PROJECT_NAME} "llama") execute_process(COMMAND ${CMAKE_AR} /def:${CMAKE_JS_NODELIB_DEF} /out:${CMAKE_JS_NODELIB_TARGET} ${CMAKE_STATIC_LINKER_FLAGS})
node-llama-cppのコードを見てみた import {createRequire} from "module"; const require = createRequire(import.meta.url); export
async function loadBin(): Promise<LlamaCppNodeModule> { const usedBinFlag = await getUsedBinFlag(); if (usedBinFlag === "prebuiltBinaries") { const prebuildBinPath = await getPrebuildBinPath(); return require(prebuildBinPath); } }
LangChain.jsのコードを見てみた import { LlamaModel, LlamaContext, LlamaChatSession } from "node-llama-cpp"; import
{ LlamaBaseCppInputs, createLlamaModel, createLlamaContext, createLlamaSession} from "../utils/llama_cpp.js"; export class LlamaCpp extends LLM<LlamaCppCallOptions> { _model: LlamaModel; _context: LlamaContext; _session: LlamaChatSession; constructor(inputs: LlamaCppInputs) { this._model = createLlamaModel(inputs); this._context = createLlamaContext(this._model, inputs); this._session = createLlamaSession(this._context); } async _call(prompt: string): Promise<string> { const promptOptions = {}; const completion = await this._session.prompt(prompt, promptOptions); return completion; } } https://github.com/langchain-ai/langchainjs/blob/main/libs/langchain-community/src/llms/llama_cpp.ts
llama.cppのコードを見てみた ifdef LLAMA_METAL MK_CPPFLAGS += -DGGML_USE_METAL MK_LDFLAGS += -framework Foundation
-framework Metal -framework MetalKit OBJS += ggml-metal.o ifdef LLAMA_METAL_NDEBUG MK_CPPFLAGS += -DGGML_METAL_NDEBUG endif endif # LLAMA_METAL ifdef LLAMA_METAL ggml-metal.o: ggml-metal.m ggml-metal.h $(CC) $(CFLAGS) -c $< -o $@ endif # LLAMA_METAL https://github.com/ggerganov/llama.cpp/blob/master/Makefile
参考:Ollama🦙 https://ollama.ai/
おわりに Llama 2すごい llama.cppすごい Node-APIすごい LLMはPythonじゃなくてもいんじゃね? generated by chatgpt