メインコンテンツまでスキップ

GenAIをグラフに組み込む

項目
カテゴリGenAI
難易度上級
推定所要時間20-25 minutes
ラベルgenai, graph, composition, streaming, advanced

ほとんどの生成AIアプリケーションは、直接的なモデルAPIから始めるべきです。生成AIが他のモデルと連携する必要がある場合、グラフによる構成が役立ちます。 Neat ステージ、名前付き入力、名前付き出力、ルーティング、またはアプリケーションレベルのオーケストレーション。

ウォークスルー

GenAI グラフフラグメントを作成

タスク固有のモデルハンドルを作成し、グラフフラグメントのオプションを設定し、パブリックモデルを構築します。 Graph フラグメント。

このビジョンと言語のフラグメントは、 prompt, imageおよび use_cached_image 入力に加えて tokens, done, encodedおよび error 出力。音声文字起こし機能の一部は、次の機能を提供します。 audio そして audio_path 入力に加えて tokens, doneおよび error 出力。

SpeechTranscriberOptions デフォルトでは、言語を自動的に検出し、 文字起こしを行います。設定してください。 taskASRTask::Translate C++または ASRTask.Translate Pythonで音声を聞き取り、英語に翻訳します。 done bundleは、検出されたソース言語を報告し、利用可能な場合は no_speech_prob そして avg_logprob.

tutorials/022_compose_genai_into_graph/compose_genai_into_graph.cpp
auto model = std::make_shared<genai::VisionLanguageModel>(args.model);

genai::VisionLanguageOptions options;
options.system_prompt = "You are concise.";
options.max_new_tokens = 96;
options.streaming = true;
options.encode_images_on_input = false;

simaai::neat::Graph genai_fragment =
genai::graphs::VisionLanguage(model, options, "genai_stage");

フラグメントをアプリのグラフに追加します

このフラグメントを、より大規模なアプリケーションのグラフに追加します。このフラグメントは、公開エンドポイントの名前を保持するため、アプリケーションコードは名前を使用してデータをプッシュおよびプルできます。

tutorials/022_compose_genai_into_graph/compose_genai_into_graph.cpp
simaai::neat::Graph app("genai_app");
app.add(genai_fragment);
std::cout << app.describe() << "\n";

グラフの入力のビルドとプッシュ

グラフを組み込んで Run、イメージサンプルをプッシュして image 入力後、テキストサンプルをプッシュします。 prompt 入力を与え、GenAIステージでトークンを生成させます。

tutorials/022_compose_genai_into_graph/compose_genai_into_graph.cpp
simaai::neat::Run run = app.build();
if (!run.push("image", make_image_sample(args.image))) {
throw std::runtime_error("push(image) failed: " + run.last_error());
}
if (!run.push("prompt", make_text_sample("prompt", "Describe this image in one sentence."))) {
throw std::runtime_error("push(prompt) failed: " + run.last_error());
}

トークンと完了メタデータを取得

~から取得 tokens ~まで done サンプルが到着しました。 done サンプルは、生成されたトークンの数や完了理由などのフィールドを含む一連のデータです。

tutorials/022_compose_genai_into_graph/compose_genai_into_graph.cpp
std::cout << "assistant: ";
for (int i = 0; i < 256; ++i) {
if (auto token = run.pull("tokens", 250)) {
std::cout << sample_text(*token) << std::flush;
continue;
}
if (auto done = run.pull("done", 10)) {
(void)done;
break;
}
if (auto error = run.pull("error", 10)) {
throw std::runtime_error(sample_text(*error));
}
}
std::cout << "\n";
run.close();

実行

~において Modalix DevKitLFM2-VL 1.6B VLMをダウンロードしてください。 Hugging Face を使用して LLiMa CLI:

llima pull LFM2-VL-1.6B-a16w4

チュートリアルを次の場所で実行してください。 Modalix ~とともに DevKit-ローカルモデルディレクトリとローカルイメージ:

C++ (prebuilt):

./lib/sima-neat/tutorials/tutorial_022_compose_genai_into_graph \
--model /media/nvme/llima/models/LFM2-VL-1.6B-a16w4 \
--image share/sima-neat/tutorials/assets/fronalpstock_1330.jpg

C++ (build from source):

./build.sh --target tutorial_022_compose_genai_into_graph
./build/tutorials-standalone/tutorial_022_compose_genai_into_graph \
--model /media/nvme/llima/models/LFM2-VL-1.6B-a16w4 \
--image share/sima-neat/tutorials/assets/fronalpstock_1330.jpg

期待される出力は、グラフの説明と、tokensの出力から取得したストリーミング形式の回答を表示します。

実践

GenAIがより大規模なアプリケーションのグラフの一部である場合に、このパターンを使用します。単純なリクエスト/レスポンスアプリケーションコードでは、GenAIModelVisionLanguageModel、およびASRModelへの直接の呼び出しを維持します。

完全なソース

完全なソースプログラムを表示
tutorials/022_compose_genai_into_graph/compose_genai_into_graph.cpp
#include "neat.h"

#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>

#include <filesystem>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>

namespace genai = simaai::neat::genai;

struct Args {
std::filesystem::path model;
std::filesystem::path image;
};

Args parse_args(int argc, char** argv) {
Args args;
for (int i = 1; i < argc; ++i) {
const std::string arg = argv[i];
if (arg == "--model" && i + 1 < argc) {
args.model = argv[++i];
} else if (arg == "--image" && i + 1 < argc) {
args.image = argv[++i];
} else {
throw std::runtime_error(
"usage: compose_genai_into_graph --model <vlm_model_dir> --image <image>");
}
}
if (args.model.empty() || args.image.empty()) {
throw std::runtime_error("missing required --model <vlm_model_dir> or --image <image>");
}
return args;
}

simaai::neat::Sample make_text_sample(const std::string& port, const std::string& text) {
return simaai::neat::make_tensor_sample(port, simaai::neat::Tensor::from_text(text));
}

simaai::neat::Sample make_image_sample(const std::filesystem::path& image_path) {
cv::Mat bgr = cv::imread(image_path.string(), cv::IMREAD_COLOR);
if (bgr.empty()) {
throw std::runtime_error("failed to read image: " + image_path.string());
}

cv::Mat rgb;
cv::cvtColor(bgr, rgb, cv::COLOR_BGR2RGB);
return simaai::neat::make_tensor_sample(
"image", simaai::neat::Tensor::from_cv_mat(rgb, simaai::neat::ImageSpec::PixelFormat::RGB,
simaai::neat::TensorMemory::CPU));
}

std::string sample_text(const simaai::neat::Sample& sample) {
if (sample.kind == simaai::neat::SampleKind::Tensor && sample.tensor.has_value()) {
return sample.tensor->to_text();
}
if (sample.kind == simaai::neat::SampleKind::TensorSet && sample.tensors.size() == 1U) {
return sample.tensors.front().to_text();
}
return {};
}

int main(int argc, char** argv) {
try {
const Args args = parse_args(argc, argv);

auto model = std::make_shared<genai::VisionLanguageModel>(args.model);

genai::VisionLanguageOptions options;
options.system_prompt = "You are concise.";
options.max_new_tokens = 96;
options.streaming = true;
options.encode_images_on_input = false;

simaai::neat::Graph genai_fragment =
genai::graphs::VisionLanguage(model, options, "genai_stage");

simaai::neat::Graph app("genai_app");
app.add(genai_fragment);
std::cout << app.describe() << "\n";

simaai::neat::Run run = app.build();
if (!run.push("image", make_image_sample(args.image))) {
throw std::runtime_error("push(image) failed: " + run.last_error());
}
if (!run.push("prompt", make_text_sample("prompt", "Describe this image in one sentence."))) {
throw std::runtime_error("push(prompt) failed: " + run.last_error());
}

std::cout << "assistant: ";
for (int i = 0; i < 256; ++i) {
if (auto token = run.pull("tokens", 250)) {
std::cout << sample_text(*token) << std::flush;
continue;
}
if (auto done = run.pull("done", 10)) {
(void)done;
break;
}
if (auto error = run.pull("error", 10)) {
throw std::runtime_error(sample_text(*error));
}
}
std::cout << "\n";
run.close();

return 0;
} catch (const std::exception& e) {
std::cerr << "error: " << e.what() << "\n";
return 1;
}
}

ソース