Upgrade to PRO for Only $50/Year—Limited-Time Offer! 🔥
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Node.jsでllama_2_.pdf
Search
Optimisuke
February 21, 2024
Technology
0
210
Node.jsでllama_2_.pdf
kansai.ts #5 2024/02/21 で発表したスライドです。
Optimisuke
February 21, 2024
Tweet
Share
More Decks by Optimisuke
See All by Optimisuke
量子コンピュータ勉強会#1
optimisuke
0
27
LangChainやるならPythonよりTypeScriptの方がいんじゃね?
optimisuke
1
1.2k
オンオフの切り替え
optimisuke
0
60
Other Decks in Technology
See All in Technology
文字列の並び順 / Unicode Collation
tmtms
3
620
ウェルネス SaaS × AI、1,000万ユーザーを支える 業界特化 AI プロダクト開発への道のり
hacomono
PRO
0
270
アプリにAIを正しく組み込むための アーキテクチャ── 国産LLMの現実と実践
kohju
0
130
MLflowダイエット大作戦
lycorptech_jp
PRO
1
150
Identity Management for Agentic AI 解説
fujie
0
230
Lessons from Migrating to OpenSearch: Shard Design, Log Ingestion, and UI Decisions
sansantech
PRO
1
160
MariaDB Connector/C のcaching_sha2_passwordプラグインの仕様について
boro1234
0
950
IAMユーザーゼロの運用は果たして可能なのか
yama3133
2
510
普段使ってるClaude Skillsの紹介(by Notebooklm)
zerebom
1
200
AWSを使う上で最低限知っておきたいセキュリティ研修を社内で実施した話 ~みんなでやるセキュリティ~
maimyyym
2
1.9k
Database イノベーショントークを振り返る/reinvent-2025-database-innovation-talk-recap
emiki
0
240
JEDAI認定プログラム JEDAI Order 2026 エントリーのご案内 / JEDAI Order 2026 Entry
databricksjapan
0
150
Featured
See All Featured
Introduction to Domain-Driven Design and Collaborative software design
baasie
1
500
The Anti-SEO Checklist Checklist. Pubcon Cyber Week
ryanjones
0
23
Leveraging Curiosity to Care for An Aging Population
cassininazir
1
130
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
359
30k
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
0
22
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
55
3.2k
A brief & incomplete history of UX Design for the World Wide Web: 1989–2019
jct
1
260
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
254
22k
The B2B funnel & how to create a winning content strategy
katarinadahlin
PRO
0
170
Jamie Indigo - Trashchat’s Guide to Black Boxes: Technical SEO Tactics for LLMs
techseoconnect
PRO
0
29
Ruling the World: When Life Gets Gamed
codingconduct
0
92
Build The Right Thing And Hit Your Dates
maggiecrowley
38
3k
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