From bcb0a8c74530d7b5d8d35ef546e0567489769411 Mon Sep 17 00:00:00 2001 From: Pension_qe <97943633+AbyssGG@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:28:06 +0800 Subject: [PATCH] feat: add optional GenAI API for 0.2.2 --- CHANGELOG.md | 35 +- NOTICE | 17 +- README.md | 14 +- README_zh-CN.md | 8 +- RELEASE_NOTES.md | 42 +- docs/README.md | 6 +- docs/api-overview.md | 23 +- docs/c-api-coverage.md | 80 +- docs/compatibility.md | 10 + docs/genai-audit.md | 59 ++ docs/genai.md | 175 ++++ docs/roadmap.md | 13 +- openvino.nimble | 29 +- src/openvino.nim | 2 + src/openvino/genai.nim | 1266 +++++++++++++++++++++++++ src/openvino/preprocess.nim | 3 +- src/openvino/private/genai_bridge.nim | 71 ++ src/openvino/raw.nim | 14 +- src/openvino/raw/genai.nim | 11 + src/openvino/raw/genai/api.nim | 1019 ++++++++++++++++++++ src/openvino/raw/genai/common.nim | 58 ++ src/openvino/raw/genai/loader.nim | 118 +++ src/openvino/tensor.nim | 69 +- src/openvino/version.nim | 2 +- tests/genai/tgenai_integration.nim | 248 +++++ tests/integration/tcpu_inference.nim | 32 + tests/packaging/consumer.nim | 3 + tests/unit/tgenai_surface.nim | 46 + 28 files changed, 3394 insertions(+), 79 deletions(-) create mode 100644 docs/genai-audit.md create mode 100644 docs/genai.md create mode 100644 src/openvino/genai.nim create mode 100644 src/openvino/private/genai_bridge.nim create mode 100644 src/openvino/raw/genai.nim create mode 100644 src/openvino/raw/genai/api.nim create mode 100644 src/openvino/raw/genai/common.nim create mode 100644 src/openvino/raw/genai/loader.nim create mode 100644 tests/genai/tgenai_integration.nim create mode 100644 tests/unit/tgenai_surface.nim diff --git a/CHANGELOG.md b/CHANGELOG.md index 2eaa0f6..fd75019 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,40 @@ and the OpenVINO runtime baseline evolve independently: - **OpenVINO compatibility** changes to the pinned runtime and header baseline. -## Unreleased +## 0.2.2 + +Release focused on the optional OpenVINO GenAI C API and remaining correctness +fixes. + +### Nim API + +- Added 150 fixed-signature raw declarations from the OpenVINO GenAI + `2026.4.1.0` C headers, tracked all 153 C symbols, and added a managed API + for LLM text and chat generation, VLM, Whisper, generation settings, + JSON/chat containers, results, synchronous streaming callbacks and + performance metrics. Raw declarations are available from + `openvino/raw/genai`; importing `openvino` does not load the optional GenAI + library. +- Added a private C adapter for the three variadic pipeline constructors. It + forwards at most 16 string property pairs without a Nim C-varargs ABI. +- Added GenAI loader configuration, runtime and model setup documentation, and + real-model LLM and Whisper integration checks under ORC and ARC. +- Reject embedded NUL characters in GenAI model paths, device names, prompts, + JSON, settings and pipeline properties before passing strings to C. +- Clear an empty stop-string list through a non-null sentinel pointer required + by the upstream C implementation. +- Report request-returned tensor storage ownership as unknown rather than + incorrectly claiming OpenVINO owns a potentially caller-provided buffer. + `storageOwnership` distinguishes unknown, OpenVINO-owned and caller-owned; + `ownsStorage` returns true only when ownership is known. + +### OpenVINO compatibility + +- GenAI declarations target OpenVINO GenAI `2026.4.1.0`, paired with Runtime + `2026.4.1`. Real LLM and Whisper generation was verified on Linux x86_64 + with CPU; VLM, Windows/macOS, GPU and NPU GenAI execution remain unverified. +- The scope is the complete pinned GenAI C API. C++-only image/video + generation, speech generation, embeddings and reranking are not exposed. ## 0.2.1 diff --git a/NOTICE b/NOTICE index 03f6a58..d1182ef 100644 --- a/NOTICE +++ b/NOTICE @@ -20,6 +20,13 @@ e213a14). The SHA-256 of all 18 headers is recorded in docs/c-api-coverage.md an docs/resonance-audit.md, and tests/abi compares the declarations against headers compiled by a C compiler rather than against a transcription. +The optional modules under src/openvino/raw/genai were written by hand against +the OpenVINO GenAI C headers from tag 2026.4.1.0, commit +ab01d1771e4adaa0e1e08e9d630def170572506c. Their eight functional header +SHA-256 digests and the 153-symbol coverage contract are recorded in +docs/c-api-coverage.md. The generated C bridge for the three variadic pipeline +constructors is original adapter code; no upstream source file is copied. + Whether that requires attribution here was considered rather than assumed. The conclusion, recorded so that a reader need not repeat the reasoning: @@ -38,11 +45,11 @@ conclusion, recorded so that a reader need not repeat the reasoning: upstream work has one whose contents are attributable. This file therefore states the relationship and the provenance rather than copying anything. -No third-party source code is bundled. The package depends on the OpenVINO -runtime at run time only, loads it by name through the dynamic loader, and never -ships or installs it. The only third-party artefact this repository references is -the pinned OpenVINO wheel that CI downloads by URL and sha256, which is recorded -in ci/install-openvino.py and is not redistributed. +No third-party source code or native library is bundled. The package depends on +OpenVINO Runtime at run time and optionally on matching GenAI and Tokenizers +libraries; it loads them through the dynamic loader and never ships or installs +them. CI downloads the pinned OpenVINO wheel by URL and SHA-256, as recorded in +ci/install-openvino.py; that artifact is not redistributed. Test fixtures diff --git a/README.md b/README.md index 9a1e22d..41470fa 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE) [![Nim](https://img.shields.io/badge/Nim-%E2%89%A52.0.0-yellow.svg)](https://nim-lang.org/) [![OpenVINO](https://img.shields.io/badge/OpenVINO-2026.4.x-6b4fbb.svg)](https://docs.openvino.ai/) -[![Status](https://img.shields.io/badge/status-v0.2.0-brightgreen.svg)](https://github.com/AbyssGG/OpenVINO-Nim-API/releases/tag/v0.2.0) +[![Status](https://img.shields.io/badge/status-v0.2.2-brightgreen.svg)](https://github.com/AbyssGG/OpenVINO-Nim-API/releases/tag/v0.2.2) **English** | [简体中文](README_zh-CN.md) @@ -21,8 +21,11 @@ Corporation.** OpenVINO is a trademark of Intel Corporation. ## Status -Version `0.2.1` contains correctness and memory safety fixes; see the -[release notes](RELEASE_NOTES.md). +Version `0.2.2` adds the optional OpenVINO GenAI C API for text/chat, visual +language and Whisper workloads, and fixes remaining correctness issues. See +the [release notes](RELEASE_NOTES.md) and [GenAI guide](docs/genai.md). GenAI +uses separately installed matching native libraries; only Linux x86_64 CPU +LLM and Whisper execution has been verified so far. Version `0.2.0` was released on 2026-10-18 and adds asynchronous inference, dynamic and partial shapes with reshape, and declarative layout and @@ -66,10 +69,10 @@ already works unless it says so. ## Feature overview -| Capability | 0.2.0 status | Notes | +| Capability | 0.2.2 status | Notes | |---|---|---| | Managed Nim API | Available | `Core`, `Model`, `CompiledModel`, `InferRequest`, `Tensor`, shapes and properties | -| Raw C ABI layer | Available | Import it explicitly with `openvino/raw`; pinned to OpenVINO `2026.4.1` headers | +| Raw C ABI layers | Available | Import `openvino/raw` for Runtime `2026.4.1` or `openvino/raw/genai` for GenAI `2026.4.1.0` headers | | Synchronous CPU inference | Available | Windows and Linux x86_64 are verified in CI and on clean hosts | | Synchronous GPU & NPU inference | Available (Windows x86_64) | Verified on Intel iGPU (`GPU.0`), NVIDIA dGPU (`GPU.1`) and Intel AI Boost (`NPU`) via `nimble testHardware` | | Runtime discovery and diagnostics | Available | Version, device listing, symbol checks and actionable loader errors | @@ -77,6 +80,7 @@ already works unless it says so. | Asynchronous inference | Available (new in 0.2.0) | `startAsync`, `wait`, `waitFor`, `cancel` and `CompletionQueue`; no Nim code runs on OpenVINO threads, so user callbacks are deliberately not offered | | Dynamic shapes and reshape | Available (new in 0.2.0) | `PartialShape`, `Port.partialShape` and `Model.reshape`; the NPU plugin needs bounded or static shapes | | Layout and preprocessing | Available (new in 0.2.0) | `Layout` and a declarative `PreprocessPlan` applied in one call | +| Optional OpenVINO GenAI C API | Available (new in 0.2.2) | All 153 pinned C symbols represented by 150 raw declarations and a C adapter for three variadic constructors; managed LLM/chat, VLM and Whisper APIs; real-model CPU checks cover LLM and Whisper on Linux x86_64 | | Request pools, remote contexts | Roadmap | See [the roadmap](docs/roadmap.md) | The roadmap is deliberately explicit about what is not implemented. See diff --git a/README_zh-CN.md b/README_zh-CN.md index c2ed0c1..56129bd 100644 --- a/README_zh-CN.md +++ b/README_zh-CN.md @@ -2,7 +2,7 @@ [English](README.md) | **简体中文** -OpenVINO Runtime C API 的 Nim 绑定。项目主文档以英文维护,本页提供中文 +OpenVINO Runtime 与 GenAI C API 的 Nim 绑定。项目主文档以英文维护,本页提供中文 入口和关键说明;API 名称、代码示例和兼容性结论以英文文档为准。 **本项目由社区维护,不是 Intel 或 OpenVINO 官方项目,也没有得到 Intel @@ -10,7 +10,10 @@ Corporation 的认可或附属关系。** OpenVINO 是 Intel Corporation 的商 ## 项目状态 -版本 `0.2.1` 包含正确性和内存安全修复,详见[发布说明](RELEASE_NOTES.md)。 +版本 `0.2.2` 增加可选的 OpenVINO GenAI C API,覆盖文本/聊天生成、视觉语言生成和 +Whisper,并修复剩余正确性问题。详见[发布说明](RELEASE_NOTES.md)和 +[GenAI 指南](docs/genai.md)。GenAI 需要单独安装匹配的本机库;目前仅在 Linux +x86_64 CPU 上对真实 LLM 和 Whisper 模型完成验证。 版本 `0.2.0` 已于 2026-10-18 发布([GitHub Release](https://github.com/AbyssGG/OpenVINO-Nim-API/releases/tag/v0.2.0)),新增异步推理(`startAsync`、`wait`、 `waitFor`、`cancel` 与 `CompletionQueue`,不在 OpenVINO 线程上运行任何 Nim 代码, @@ -102,6 +105,7 @@ Nimble 官方包索引条目已提交([nim-lang/packages #3578](https://github - [英文入门指南](docs/getting-started.md) - [英文 API overview](docs/api-overview.md) - [英文 C API coverage](docs/c-api-coverage.md) +- [英文 GenAI guide](docs/genai.md) - [英文 compatibility matrix](docs/compatibility.md) - [英文 troubleshooting](docs/troubleshooting.md) - [贡献指南](CONTRIBUTING.md) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 09c3f1b..a7dda88 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,21 +1,39 @@ -# OpenVINO Nim API 0.2.1 +# OpenVINO Nim API 0.2.2 -This patch release fixes correctness and memory safety issues in the -community-maintained Nim bindings for the OpenVINO Runtime C API. +This release adds optional GenAI support and fixes correctness issues in the +community-maintained Nim bindings for the OpenVINO Runtime and GenAI C APIs. + +## Added + +- Raw declarations for all 150 fixed-signature functions in OpenVINO GenAI + `2026.4.1.0` C headers, tracking of all 153 C symbols, and a C adapter for + the three variadic pipeline constructors. +- Managed LLM text/chat generation, synchronous streaming, VLM generation, + Whisper transcription, generation settings, JSON/chat history, results and + performance metrics. +- Lazy GenAI library loading and a C adapter for its variadic pipeline + constructors. Core `import openvino` continues to work without GenAI installed. +- Real-model integration tests for LLM and Whisper under ORC and ARC. +- Correct handling of an empty stop-string list and embedded NUL strings. ## Fixes -- Reject tensor byte copies of Nim types containing managed references. -- Validate every shape dimension even when a zero dimension is present. -- Reject embedded NUL characters in C-bound names, properties, devices and - file paths rather than silently truncating them. -- Avoid overflowing a completion queue's deadline for very long timeouts. +- Report request-returned tensor storage ownership as unknown unless the + runtime contract guarantees ownership. +- Reject embedded NUL characters across GenAI inputs instead of silently + truncating strings at the C boundary. +- Carry forward the 0.2.1 fixes: reject tensor byte copies containing Nim + references, validate negative shape dimensions even with zero dimensions, + reject embedded NUL in existing C-bound strings, and guard long timeout + deadline arithmetic. ## Compatibility -The package targets OpenVINO `2026.4.1` and requires Nim `2.0.0` or newer. -The changes reject inputs that could previously cause incorrect behaviour. -The 0.2.1 changes have not been tested on GPU or NPU hardware. -See [the compatibility matrix](docs/compatibility.md) for previous releases. +The package targets OpenVINO Runtime `2026.4.1` and GenAI `2026.4.1.0`, and +requires Nim `2.0.0` or newer. Real GenAI execution was tested on Linux x86_64 +CPU for LLM and Whisper. VLM, Windows/macOS, GPU and NPU GenAI remain unverified. +This release covers the upstream GenAI **C API**; C++-only image/video +generation, speech generation, embeddings and reranking are outside its scope. +See [the compatibility matrix](docs/compatibility.md) and [GenAI guide](docs/genai.md). For the complete change list, see [CHANGELOG.md](CHANGELOG.md). diff --git a/docs/README.md b/docs/README.md index c5c38de..b79ec5a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,6 +11,7 @@ provides a bilingual entry point. |---|---| | I am new to the project | [Getting started](getting-started.md) | | I need the public types and functions | [API overview](api-overview.md) | +| I need optional text, vision or speech generation | [GenAI guide](genai.md) | | I need the generated symbol pages | [API index](api-index.html) after `nimble docs` | | I need to know what really works | [Compatibility](compatibility.md) | | I need to diagnose a loader or runtime failure | [Troubleshooting](troubleshooting.md) | @@ -27,8 +28,9 @@ From the repository root: nimble docs ``` -The task generates a page for every public managed module, the explicit raw -entry point, and a merged symbol index under `build/docs`. The output is an +The task generates a page for every public managed module, including optional +GenAI, both explicit raw entry points, and a merged symbol index under +`build/docs`. The output is an artifact in CI and can also be opened locally at `build/docs/index.html`. ## Optional GitHub Pages deployment diff --git a/docs/api-overview.md b/docs/api-overview.md index ea44827..63759b5 100644 --- a/docs/api-overview.md +++ b/docs/api-overview.md @@ -1,14 +1,15 @@ # API overview -OpenVINO Nim API has a small managed surface and an explicit raw C layer. The -managed surface is the compatibility target for application code; raw modules -mirror the pinned OpenVINO 2026.4 C headers and are intentionally less safe. +OpenVINO Nim API has a managed surface and explicit raw C layers. The managed +surface is the compatibility target for application code; raw modules mirror +the pinned OpenVINO Runtime 2026.4 and GenAI 2026.4.1.0 C headers and are +intentionally less safe. ## Managed modules | Module | Main symbols | Responsibility | |---|---|---| -| `openvino` | `newCore`, `RuntimeVersion`, exceptions | Stable import root; raw declarations are not re-exported | +| `openvino` | `newCore`, `RuntimeVersion`, exceptions, GenAI API | Stable import root; raw declarations are not re-exported | | `openvino/core` | `Core`, `runtimeVersion`, `availableDevices` | Runtime loading, model reading, compiling and import | | `openvino/model` | `Model`, `inputCount`, `outputCount`, `reshape` | Model metadata, const ports and reshaping | | `openvino/node` | `Port`, `name`, `elementType`, `shape`, `partialShape`, `isDynamic` | Read-only input and output port metadata | @@ -21,6 +22,7 @@ mirror the pinned OpenVINO 2026.4 C headers and are intentionally less safe. | `openvino/properties` | `Property`, `enableProfiling`, `cacheDirectory` | Safe string-valued runtime properties | | `openvino/errors` | `OpenVinoError`, `OpenVinoBusyError`, `OpenVinoCancelledError`, `OpenVinoArgumentError`, `OpenVinoLibraryError`, `OpenVinoVersionError` | Runtime, busy, cancelled, argument, loader and version failures | | `openvino/version` | `PackageVersion`, `TargetOpenVinoVersion` | Package metadata and the pinned runtime baseline | +| `openvino/genai` | `LlmPipeline`, `VlmPipeline`, `WhisperPipeline`, configs, results | Optional managed GenAI C API; loaded only when used | All managed handles have an idempotent `close()` and a destructor backstop. Copying a managed value shares the native handle and closed state; it does not @@ -124,6 +126,14 @@ as the request exists, and its function must not allocate, raise or touch Nim memory. The exact symbol list and header checksums are in [C API coverage](c-api-coverage.md). +The managed GenAI API covers the pinned GenAI C functions for text generation +and chat, visual-language generation, Whisper transcription, JSON containers, +generation settings, results and metrics. It is optional: importing +`openvino` does not load GenAI, and the GenAI C library plus its matching +Runtime and Tokenizers components are required only when a GenAI operation is +called. Streaming handlers run synchronously on the calling thread. See the +[GenAI guide](genai.md) for installation, examples and the C++-only boundary. + ## Typical call sequence 1. Create a `Core` with `newCore()`. @@ -148,6 +158,11 @@ checks element width and size, but does not convert data or distinguish integer and floating-point types of the same width. Match the Nim data type to the model's declared element type. +`storageOwnership` reports `soOpenVinoOwned`, `soCallerOwned` or `soUnknown`. +Request-returned tensors have unknown storage ownership: keep any external +buffer alive until all uses of the bound tensor have finished. `ownsStorage` +returns true only for known OpenVINO-owned storage. + For repeated inference, keep the compiled model and request, update input storage with `copyFrom`, and call `infer()` again. `copyFrom` requires exactly the tensor's element count. Read or copy each output before the next inference diff --git a/docs/c-api-coverage.md b/docs/c-api-coverage.md index 4433209..688a20a 100644 --- a/docs/c-api-coverage.md +++ b/docs/c-api-coverage.md @@ -1,12 +1,10 @@ # OpenVINO C API coverage This document is the coverage contract between the pinned OpenVINO `2026.4.1` -(and `2026.4.0`) headers and `src/openvino/raw/`. It describes the current -repository, not an old implementation plan. Every item marked **bound** is -present in the raw layer and is exercised by the ABI or smoke checks; every -item marked **deferred** is intentionally not bound. The `0.2.0` additions -(asynchronous inference, partial shapes, reshape, layouts and preprocessing) -are bound in the raw layer; their managed API is under development. +(and `2026.4.0`) headers, the GenAI `2026.4.1.0` C headers, and +`src/openvino/raw/`. It describes the current repository, not an old +implementation plan. A header being bound does not mean every function has a +real-model behaviour test; the test section states what has been exercised. ## Pinned source of truth @@ -28,6 +26,47 @@ The 18 installed header SHA-256 values are recorded in the repository history and are checked against the pinned runtime by CI. The ABI probe also checks the values and layout that cannot be established by a Nim declaration alone. +## GenAI C API source of truth + +| Item | Value | +|---|---| +| Upstream release | OpenVINO GenAI `2026.4.1.0` | +| Upstream tag and commit | `2026.4.1.0`, `ab01d1771e4adaa0e1e08e9d630def170572506c` | +| Header location | `src/c/include/openvino/genai/c/*.h` | +| Runtime library | `openvino_genai_c` plus matching GenAI, Runtime and Tokenizers libraries | +| Raw module | `openvino/raw/genai` | +| Managed module | `openvino/genai` | + +The eight functional GenAI headers are `chat_history.h`, +`generation_config.h`, `json_container.h`, `llm_pipeline.h`, `perf_metrics.h`, +`vlm_pipeline.h`, `whisper_generation_config.h`, and `whisper_pipeline.h`. +Their 153 function symbols are tracked by `GenAiApiSymbols`; 150 fixed-signature +functions use lazy dynamic bindings. The three pipeline constructors use C +varargs. A private C adapter invokes them without declaring C varargs to Nim, +and forwards at most 16 string property pairs. All normal C calls remain +lazily resolved, and importing `openvino` does not load GenAI. + +The Linux GenAI library candidates are `libopenvino_genai_c.so`, then +`libopenvino_genai_c.so.2641` and earlier patch SONAMEs. Windows and macOS +candidates are declared, but GenAI has only been tested on Linux x86_64 here. +Set `OPENVINO_GENAI_C_LIBRARY` or compile with +`-d:openvinoGenAiLib=` when the library is not on the loader path. +The tokenizer plugin path remains the GenAI runtime's responsibility and is +selected with `OPENVINO_TOKENIZERS_PATH_GENAI`. + +The eight functional header digests from the pinned source tree are: + +```text +d4e84166e9ee7cb8ba18569eb16a58a05bef298ce3cbf40a15c4a04d232fe3de chat_history.h +8a75b60cef8df22f10901804fa59d89c93994cc33f7444231bd0173904a1dc52 generation_config.h +e920475198b8a4ca416194d1f361ff128c04aaf82939a9aea2989ce7e2a42b39 json_container.h +3e63cc496170ad137f38bd30dc16a15b172210553521d5038066284fd54c2c49 llm_pipeline.h +2376f39a0a5f2dcd3055b86366c3267a2c34fd027fe74315d2a2760415f0c9ff perf_metrics.h +5a4ac6ba23b676a9ac523f3f573121ddf7dce7a8a418efdd8b3220618f39714a vlm_pipeline.h +1789c97d2d46fd92e7ae64c4b41b066b33995cc6966341d25cf8aad53f1332b3 whisper_generation_config.h +9072eb2e1b2f3b0f525e1177cfe4de64dcff2bb641fff99ef8d17b82db8dddfb whisper_pipeline.h +``` + The recorded header digests are: ```text @@ -68,6 +107,7 @@ a12a4c241bccbc9cd3cf68f39b13c91701a78cd062a97004ae8f1612b10d4650 ov_shape.h | `ov_partial_shape.h` | `raw/partial_shape` | `ov_partial_shape_t` and all eight functions; the managed layer uses only `ov_partial_shape_free` | | `ov_layout.h` | `raw/layout` | Layout create, format and release | | `ov_prepostprocess.h` | `raw/prepostprocess` | All 39 non-variadic functions, the seven opaque child types and the color format, resize algorithm and padding mode enumerations | +| GenAI's eight C headers | `raw/genai` and `genai` | All 153 C symbols, including the three variadic constructors via the adapter; managed LLM/chat, VLM, Whisper, JSON, settings, results, callbacks and metrics | The `0.2.0` additions were checked against the upstream C binding sources at tag `2026.4.0` and measured on the runtime in Phase 0 of the 0.2 plan. The @@ -76,6 +116,22 @@ evidence, including the upstream defects listed below, is recorded in [ADR 0004](decisions/0004-partial-shape-representation.md) and [ADR 0005](decisions/0005-preprocessing-api.md). +## GenAI test coverage + +The runtime-free unit suite checks that importing the optional managed and raw +modules does not load native libraries, and checks the tracked symbol set. The +real-model `nimble testGenAi` suite resolves all 153 symbols, tests JSON/chat +ownership, generation settings, LLM text/chat/streaming/property forwarding +and Whisper transcription/chunks/metrics on CPU under ORC and ARC. Local +validation used the pinned Linux x86_64 GenAI C API, Tokenizers and Runtime +libraries plus TinyLlama and OpenVINO Whisper Tiny models. It has not run VLM +generation against a model, nor Windows/macOS, GPU or NPU GenAI. + +The C++ GenAI API includes pipeline families that the pinned C headers do not +expose, such as image/video generation, speech generation and embedding or +reranking APIs. They are outside this C binding's coverage; see +[the GenAI guide](genai.md). + ## ABI-sensitive facts - `ov_status_e` has `OK = 0` and `-1` through `-17`; `ov_element_type_e` @@ -92,11 +148,13 @@ evidence, including the upstream defects listed below, is recorded in is zero. - The Windows Unicode path entry points are declared only on Windows and use explicit UTF-16 element widths. The managed path layer validates conversion. -- No C varargs call is bound. The managed layer uses the `_props` and - `_properties` forms so that Nim never has to guess a platform varargs ABI. - For preprocessing, `ov_preprocess_input_tensor_info_set_color_format_with_subname` - is excluded and its array form `_with_subnames` is bound; `nimble lint` - rejects any `varargs` declaration in the raw layer. +- No C varargs function is declared with Nim's `varargs` pragma. The + OpenVINO Runtime layer uses non-variadic property forms; the three GenAI + pipeline constructors use a private C adapter that forwards up to 16 + property pairs. For preprocessing, + `ov_preprocess_input_tensor_info_set_color_format_with_subname` is excluded + and its array form `_with_subnames` is bound. `nimble lint` rejects Nim + `varargs` declarations in the raw layer. - `ov_dimension_t` is `{int64 min; int64 max}` (16 bytes) and `ov_partial_shape_t` is a rank followed by a dims pointer (24 bytes on x86_64). `ov_partial_shape_t` is passed by value to the reshape functions, diff --git a/docs/compatibility.md b/docs/compatibility.md index 301a1f5..d28a5c2 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -89,6 +89,16 @@ expected values on every device. ThreadSanitizer could not be used on Linux: OpenVINO loads `libtbbbind` with `RTLD_DEEPBIND`, which the sanitizer runtime refuses. +### Optional GenAI verification (0.2.2) + +The separate OpenVINO GenAI `2026.4.1.0` C API was tested on Linux x86_64 with +the matching Runtime and Tokenizers libraries under ORC and ARC. Real CPU +generation succeeded with TinyLlama 1.1B INT4 and Whisper Tiny; the suite also +checks all 153 C API symbols, chat history, streaming stop/error handling, +properties, transcription chunks, scores and metrics. VLM execution against a +real model and GenAI on Windows, macOS, GPU or NPU have not been tested. See +[the GenAI guide](genai.md) for setup and scope. + ## Not verified These are not claimed. Some are expected to work and simply have not been run; diff --git a/docs/genai-audit.md b/docs/genai-audit.md new file mode 100644 index 0000000..0cff84a --- /dev/null +++ b/docs/genai-audit.md @@ -0,0 +1,59 @@ +# OpenVINO GenAI implementation audit + +This audit records the implementation boundary and evidence for GenAI support +in package version 0.2.2. The pinned upstream release is OpenVINO GenAI +`2026.4.1.0`, tag `2026.4.1.0`, commit +`ab01d1771e4adaa0e1e08e9d630def170572506c`, paired with the OpenVINO Runtime +`2026.4.1` baseline. + +## Scope + +The eight functional GenAI C headers expose text generation and chat, +generation settings, visual-language generation, Whisper transcription, +JSON/chat containers and performance metrics. All 153 declared function +symbols are listed in `GenAiApiSymbols`; 150 fixed-signature functions use +lazy dynamic bindings, and the three variadic pipeline constructors are +invoked through a private C adapter. The managed API is documented in +[the GenAI guide](genai.md), with raw declarations under +`openvino/raw/genai`. + +The C++ GenAI API has additional families without matching functions in these +C headers, including image/video generation, speech generation, embeddings and +reranking. They are outside this release's binding scope. “Complete” in the +release notes refers to the pinned C API surface, not all C++ GenAI features. + +## Deployment and ABI + +The official Linux `openvino-genai` 2026.4.1.0 Python wheel used during +implementation contains `libopenvino_genai.so.2641` but not a separate +`openvino_genai_c` library. The binding therefore requires a GenAI distribution +that includes `openvino_genai_c`, or a local build of that target from the +matching upstream source. It also requires matching GenAI, Runtime and +OpenVINO Tokenizers libraries. The C runtime loads lazily and independently; +importing `openvino` remains usable without the optional library. + +The three upstream pipeline constructors take C varargs. Nim does not declare +these as C varargs: `private/genai_bridge.nim` supplies a small C adapter with +a documented maximum of 16 string property pairs. Managed C strings reject +embedded NUL characters before they reach the native boundary. + +The upstream C wrapper often translates caught C++ exceptions to +`UNKNOW_EXCEPTION` (`-17`). The original C++ diagnostic is unavailable in that +case. The new standalone Whisper config's `validate()` also returned `-17` +during local validation even though the same configuration worked in real +transcription; validation behaviour is left to the upstream library and is not +claimed as a tested success. + +## Verification + +On Linux x86_64, `nimble testGenAi` passed under ORC and ARC using matching +2026.4.1 runtime, GenAI and Tokenizers libraries, a TinyLlama 1.1B INT4 model, +and an OpenVINO Whisper Tiny model. It resolved all 153 symbols, exercised +settings, JSON/chat history, LLM text and streaming generation, callback stop +and error handling, property forwarding, transcription, chunks, scores and +metrics. Whisper returned the expected phrase from the bundled test audio. + +VLM symbols and wrappers compile and resolve, but VLM generation has not yet +been run against a real model. Windows, macOS, GPU and NPU GenAI execution have +not been verified. See [C API coverage](c-api-coverage.md) for test detail and +the [GenAI guide](genai.md) for runtime setup. diff --git a/docs/genai.md b/docs/genai.md new file mode 100644 index 0000000..146d2b5 --- /dev/null +++ b/docs/genai.md @@ -0,0 +1,175 @@ +# OpenVINO GenAI + +`openvino/genai` is an optional managed API for the OpenVINO GenAI C API. It +loads independently from the core OpenVINO Runtime, so importing `openvino` +does not require the GenAI library to be installed. The first GenAI operation +loads `openvino_genai_c` and reports a `GenAiLibraryError` if it is missing or +incompatible. + +The binding tracks OpenVINO GenAI `2026.4.1.0`, upstream tag +[`2026.4.1.0`](https://github.com/openvinotoolkit/openvino.genai/tree/2026.4.1.0), +commit `ab01d1771e4adaa0e1e08e9d630def170572506c`. All 153 functions in its +C headers are represented: 150 fixed-signature functions are dynamically +bound, and the three variadic pipeline constructors use a small C ABI bridge +that accepts up to 16 string property pairs. The corresponding raw bindings are +under `openvino/raw/genai`; they are explicitly imported and do not get +re-exported from `openvino`. + +## Runtime requirements + +Install matching OpenVINO Runtime, GenAI, and OpenVINO Tokenizers components. +The GenAI C API is a separate shared library, `openvino_genai_c`; check that +your GenAI distribution includes it. The upstream Python wheel used during +implementation did not include this C library, so on Linux you may need a +GenAI distribution that packages it or build the `openvino_genai_c` target +from the matching upstream source. Keep the GenAI C++, Runtime, and Tokenizers +libraries on the platform loader path as well. +The upstream [2026.4.1.0 build guide](https://github.com/openvinotoolkit/openvino.genai/blob/2026.4.1.0/src/docs/BUILD.md) +documents source builds; the C library is installed as the `core_c_genai` +component. + +The loader checks `OPENVINO_GENAI_C_LIBRARY` first, then platform defaults. A +compile-time path can be set with `-d:openvinoGenAiLib=/full/path/to/library`. +The Tokenizers plugin is selected by the OpenVINO GenAI runtime through +`OPENVINO_TOKENIZERS_PATH_GENAI`; this package does not download or select a +plugin for you. + +| Platform | Default GenAI C library name | +|---|---| +| Windows | `openvino_genai_c.dll` | +| Linux | `libopenvino_genai_c.so`, then `libopenvino_genai_c.so.2641` and earlier `2026.4` patch SONAMEs | +| macOS | `libopenvino_genai_c.dylib` | + +The library candidates are implemented, but this project has only run the +GenAI runtime tests on Linux x86_64. Windows and macOS GenAI loading and +execution have not been verified. + +## Text generation and chat + +```nim +import openvino + +let pipeline = newLlmPipeline("models/TinyLlama", "CPU") +let settings = newGenerationConfig() +settings.setMaxNewTokens(64) +settings.setDoSample(false) +settings.validate() + +let response = pipeline.generate("Explain OpenVINO in one sentence.", settings) +echo response.text() + +let streamed = pipeline.streamGenerate( + "Give one short example.", + proc (piece: string): StreamAction = + stdout.write(piece) + streamContinue, + settings) + +echo "\nComplete streamed result: ", streamed +``` + +The synchronous generation call blocks the calling thread. A stream handler +runs synchronously from inside that call. It may return `streamContinue`, +`streamStop`, or `streamCancel`. If the handler raises a Nim `CatchableError`, +the callback contains it at the C boundary, stops generation, and raises a +`GenAiCallbackError` after the native call returns; `callbackMessage` carries +the original message. + +`ChatHistory` stores messages as `JsonContainer` values. Each message should be +a JSON object with the keys expected by the model's chat template, commonly +`role` and `content`. The history also accepts tool definitions and extra JSON +context. Pass a history to `generate` or `streamGenerate` for structured chat. + +`GenerationConfig` exposes every setting from the C API, including token +limits, stop strings and IDs, beam search, sampling, penalties, and assistant +draft controls. Generation results can return their `PerfMetrics` for token +counts, latency, throughput, tokenization and detokenization timings. + +## Vision and speech + +`VlmPipeline` accepts text and OpenVINO image tensors. The upstream C example +creates RGB images as U8 tensors shaped `[1, height, width, 3]`; keep each +`Tensor` open for the full generation call. `Tensor.unsafeNativeHandle()` is a +borrowed C pointer and does not transfer ownership. VLM generation accepts +multiple images, structured history, generation settings and streaming. + +```nim +import openvino + +let image = tensorFrom(etU8, initShape(1, height, width, 3), rgbBytes) +let pipeline = newVlmPipeline("models/vision-language", "CPU") +let response = pipeline.generate("Describe this picture.", [image]) +echo response.text() +``` + +See the upstream [C image-loading sample](https://github.com/openvinotoolkit/openvino.genai/blob/2026.4.1.0/samples/c/visual_language_chat/load_image.c) +for its input tensor layout. + +`WhisperPipeline.transcribe` accepts audio as `openArray[float32]`. Supply +normalized mono samples at 16 kHz. `WhisperGenerationConfig` supports language, +transcription/translation task, timestamps, prompts, hotwords, token IDs and +suppress-token lists. Results provide text candidates, scores, timestamped +chunks and performance metrics. + +```nim +import openvino + +let speech = newWhisperPipeline("models/whisper-tiny", "CPU") +let settings = newWhisperGenerationConfig() +settings.setLanguage("en") +settings.setTask("transcribe") +settings.setReturnTimestamps(true) +let result = speech.transcribe(samples, settings) +echo result.transcription() +for index in 0 ..< result.chunkCount(): + let chunk = result.chunkAt(index) + echo chunk.chunkTimestamps(), " ", chunk.chunkText() +``` + +The C API accepts already prepared image tensors and audio samples. It does not +provide image-file loading, audio-file decoding, resampling, or normalization; +applications supply those steps. + +## C API boundary + +This is complete coverage of the pinned upstream **C** API, not of every C++ +class in OpenVINO GenAI. The upstream C headers audited here provide text and +chat generation, VLM, Whisper, generation configs, JSON/chat containers and +metrics. Image/video generation, speech generation, embeddings/reranking, and +other C++-only pipeline families have no equivalent in those headers and are +not exposed by this release. The raw layer is available for the C functions +that do not yet have a managed convenience wrapper: + +```nim +import openvino/raw/genai +``` + +C status codes from `GenAiError` retain their numeric value. The upstream C +wrapper catches C++ exceptions and often maps them to `UNKNOW_EXCEPTION` +(`-17`); in those cases the original C++ diagnostic is not available to Nim. + +## Tests + +The runtime-free import and ABI-surface checks run with `nimble test`. To run +real LLM and Whisper tests on CPU, set these variables before `nimble +testGenAi`: + +```shell +export OPENVINO_GENAI_TEST_MODEL=/path/to/openvino-llm-model +export OPENVINO_GENAI_TEST_WHISPER_MODEL=/path/to/openvino-whisper-model +export OPENVINO_GENAI_TEST_AUDIO_F32=/path/to/mono-16khz-float32-pcm +export OPENVINO_TOKENIZERS_PATH_GENAI=/path/to/libopenvino_tokenizers.so +# Optional when the library is not on the dynamic loader path: +export OPENVINO_GENAI_C_LIBRARY=/path/to/libopenvino_genai_c.so +nimble testGenAi +``` + +The integration task checks every exported C symbol, JSON/chat ownership, +LLM text/history/streaming/property forwarding, Whisper transcription/chunks, +and runs under both ORC and ARC. It requires a local OpenVINO IR model and a +raw little-endian float32 audio sample file; tests do not download models. + +The current real-model integration suite has been run on Linux x86_64 with +OpenVINO/GenAI/Tokenizers `2026.4.1` on CPU. It covers LLM and Whisper. The VLM +API is compiled and its C symbols are checked, but has not yet been exercised +against a real VLM model in this project. diff --git a/docs/roadmap.md b/docs/roadmap.md index 5fe7124..5913b1d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -40,6 +40,17 @@ Released on 2026-10-18 as `v0.2.0`. - Official GitHub Releases (`v0.1.0`, `v0.1.1`) and Nimble package index entry (`openvino`, [nim-lang/packages #3578](https://github.com/nim-lang/packages/pull/3578)). +## Available in 0.2.2 + +- Optional raw bindings for all 153 symbols in the OpenVINO GenAI + `2026.4.1.0` C headers, with lazy library loading. +- Managed LLM/chat, VLM and Whisper APIs, generation settings, JSON containers, + streaming callbacks, results and metrics. +- Real-model CPU validation covers LLM and Whisper on Linux x86_64. VLM with a + real model and GenAI execution on Windows, macOS, GPU or NPU remain untested. +- GenAI's C++-only image/video generation, speech generation, embeddings and + reranking families remain outside the C binding scope. + ## Next priorities | Area | Why it needs design work | @@ -48,7 +59,7 @@ Released on 2026-10-18 as `v0.2.0`. | `asyncdispatch` integration | Needs evidence that waking an event loop from a non-Nim thread is safe on IOCP and epoll | | Remote contexts | Device-specific memory ownership cannot be represented by a generic pointer | | Mutable ports | Needed only for `reshape_by_ports` and port-based tensor binding | -| GenAI and task-specific helpers | These belong in separate layers, not in the small core binding | +| GenAI C++-only pipeline families | No equivalent C interface exists in the pinned headers; see [the GenAI guide](genai.md) | ## Non-goals diff --git a/openvino.nimble b/openvino.nimble index 8eabe8a..79a001a 100644 --- a/openvino.nimble +++ b/openvino.nimble @@ -66,10 +66,10 @@ proc stringMetadata(name: string): string = # # `nimble releaseCheck` closes the loop by asserting each literal against # src/openvino/version.nim, so the single source of truth still wins. -version = "0.2.1" +version = "0.2.2" author = "WANG" -description = "Community-maintained Nim bindings for the OpenVINO Runtime " & - "C API. Not an official Intel or OpenVINO project." +description = "Community-maintained Nim bindings for the OpenVINO Runtime and " & + "GenAI C APIs. Not an official Intel or OpenVINO project." license = "Apache-2.0" srcDir = "src" @@ -464,6 +464,20 @@ task testIntegration, "Run the CPU inference loop through the public API": for path in sources: exec "nim c --hints:off --path:src " & buildMode & " -r " & path +task testGenAi, "Run real-model OpenVINO GenAI integration checks": + for variable in ["OPENVINO_GENAI_TEST_MODEL", + "OPENVINO_GENAI_TEST_WHISPER_MODEL", + "OPENVINO_GENAI_TEST_AUDIO_F32", + "OPENVINO_TOKENIZERS_PATH_GENAI"]: + if getEnv(variable).len == 0: + echo "Set ", variable, + " before running this optional real-model GenAI test." + quit(1) + for memoryManager in ["orc", "arc"]: + echo "--- memory manager: ", memoryManager, " ---" + exec "nim c --hints:off --path:src --mm:" & memoryManager & + " -r tests/genai/tgenai_integration.nim" + task testHardware, "Run the GPU and NPU inference suites on a hardware host": # Optional hardware verification. Kept separate from `testIntegration` so # CPU-only CI runners do not fail for lack of an accelerator, while still @@ -503,11 +517,16 @@ task docs, "Generate API documentation for every public module": "src/openvino/compiled_model.nim", "src/openvino/infer_request.nim", "src/openvino/core.nim", + "src/openvino/genai.nim", "src/openvino/preprocess.nim", - "src/openvino/raw.nim" + "src/openvino/raw.nim", + "src/openvino/raw/genai.nim" ] for modulePath in publicModules: - exec "nim doc --hints:off --index:on --path:src " & + let outputName = + if modulePath == "src/openvino/raw/genai.nim": "--out:genai_raw.html " + else: "" + exec "nim doc --hints:off --index:on --path:src " & outputName & "--outdir:build/docs " & modulePath # Each module writes its own .idx file. Merge those indexes after all pages # exist so the generated search page covers the managed and explicit raw diff --git a/src/openvino.nim b/src/openvino.nim index b0511f1..dc2b2e8 100644 --- a/src/openvino.nim +++ b/src/openvino.nim @@ -28,10 +28,12 @@ import openvino/core import openvino/errors +import openvino/genai import openvino/preprocess import openvino/version export core export errors +export genai export preprocess export version diff --git a/src/openvino/genai.nim b/src/openvino/genai.nim new file mode 100644 index 0000000..cb14a74 --- /dev/null +++ b/src/openvino/genai.nim @@ -0,0 +1,1266 @@ +# SPDX-License-Identifier: Apache-2.0 + +## Managed, optional OpenVINO GenAI support. +## +## GenAI loads independently from the core OpenVINO Runtime. This module can be +## imported without either shared library installed; the matching GenAI C +## library is opened only when the first GenAI call is made. The underlying +## header-faithful API is available separately through `openvino/raw/genai`. + +import errors +import private/conversions +import private/genai_bridge +import private/handles +import raw/genai as rawGenAi +import tensor + +type + GenAiError* = object of CatchableError + ## A GenAI C API call returned an error status. + operation*: string + status*: cint + + GenAiLibraryError* = rawGenAi.GenAiLibraryError + ## The optional GenAI C shared library or a required symbol is unavailable. + + GenAiCallbackError* = object of CatchableError + ## A managed streaming callback raised while GenAI was generating. + callbackMessage*: string + + StopCriteria* = enum + ## Beam search stopping behaviour. + scEarly + scHeuristic + scNever + + StreamAction* = enum + ## What a managed generation streamer asks the pipeline to do next. + streamContinue + streamStop + streamCancel + + StreamHandler* = proc (piece: string): StreamAction + {.closure, raises: [CatchableError].} + ## Receives decoded text pieces synchronously during generation. + + StreamContext = object + handler: StreamHandler + callbackFailed: bool + failureMessage: string + accumulated: string + + GenerationConfig* = object + ## Owned, reusable GenAI token generation settings. + handle: Handle[ov_genai_generation_config] + + JsonContainer* = object + ## Owned JSON object/array/value used by chat histories and tool metadata. + handle: Handle[ov_genai_json_container] + + ChatHistory* = object + ## Owned sequence of OpenAI-style message objects plus tools/context. + handle: Handle[ov_genai_chat_history] + + DecodedResults* = object + ## Owned LLM generation output. + handle: Handle[ov_genai_decoded_results] + + VlmDecodedResults* = object + ## Owned visual-language generation output. + handle: Handle[ov_genai_vlm_decoded_results] + + WhisperDecodedResults* = object + ## Owned speech transcription output, including optional chunks and scores. + handle: Handle[ov_genai_whisper_decoded_results] + + WhisperChunk* = object + ## One owned timestamped Whisper transcription chunk. + handle: Handle[ov_genai_whisper_decoded_result_chunk] + + PerfMetrics* = object + ## Owned performance statistics returned by a generated result. + handle: Handle[ov_genai_perf_metrics] + + WhisperGenerationConfig* = object + ## Owned speech recognition/translation configuration. + handle: Handle[ov_genai_whisper_generation_config] + + LlmPipeline* = object + ## Owned text generation pipeline. Calls block until generation completes. + handle: Handle[ov_genai_llm_pipeline] + + VlmPipeline* = object + ## Owned visual-language pipeline. Image inputs are OpenVINO tensors. + handle: Handle[ov_genai_vlm_pipeline] + + WhisperPipeline* = object + ## Owned Whisper speech recognition pipeline. Audio is 16 kHz mono float32. + handle: Handle[ov_genai_whisper_pipeline] + +proc releaseGenerationConfig(native: ptr ov_genai_generation_config) {.nimcall.} = + ov_genai_generation_config_free(native) + +proc releaseJsonContainer(native: ptr ov_genai_json_container) {.nimcall.} = + ov_genai_json_container_free(native) + +proc releaseChatHistory(native: ptr ov_genai_chat_history) {.nimcall.} = + ov_genai_chat_history_free(native) + +proc releaseDecodedResults(native: ptr ov_genai_decoded_results) {.nimcall.} = + ov_genai_decoded_results_free(native) + +proc releaseVlmResults(native: ptr ov_genai_vlm_decoded_results) {.nimcall.} = + ov_genai_vlm_decoded_results_free(native) + +proc releaseWhisperResults(native: ptr ov_genai_whisper_decoded_results) {.nimcall.} = + ov_genai_whisper_decoded_results_free(native) + +proc releaseWhisperChunk(native: ptr ov_genai_whisper_decoded_result_chunk) {.nimcall.} = + ov_genai_whisper_decoded_result_chunk_free(native) + +proc releasePerfMetrics(native: ptr ov_genai_perf_metrics) {.nimcall.} = + ov_genai_decoded_results_perf_metrics_free(native) + +proc releaseWhisperConfig(native: ptr ov_genai_whisper_generation_config) {.nimcall.} = + ov_genai_whisper_generation_config_free(native) + +proc releaseLlmPipeline(native: ptr ov_genai_llm_pipeline) {.nimcall.} = + ov_genai_llm_pipeline_free(native) + +proc releaseVlmPipeline(native: ptr ov_genai_vlm_pipeline) {.nimcall.} = + ov_genai_vlm_pipeline_free(native) + +proc releaseWhisperPipeline(native: ptr ov_genai_whisper_pipeline) {.nimcall.} = + ov_genai_whisper_pipeline_free(native) + +proc native(config: GenerationConfig): ptr ov_genai_generation_config = + config.handle.native() + +proc native(json: JsonContainer): ptr ov_genai_json_container = + json.handle.native() + +proc native(history: ChatHistory): ptr ov_genai_chat_history = + history.handle.native() + +proc native(results: DecodedResults): ptr ov_genai_decoded_results = + results.handle.native() + +proc native(results: VlmDecodedResults): ptr ov_genai_vlm_decoded_results = + results.handle.native() + +proc native(results: WhisperDecodedResults): ptr ov_genai_whisper_decoded_results = + results.handle.native() + +proc native(chunk: WhisperChunk): ptr ov_genai_whisper_decoded_result_chunk = + chunk.handle.native() + +proc native(metrics: PerfMetrics): ptr ov_genai_perf_metrics = + metrics.handle.native() + +proc native(config: WhisperGenerationConfig): ptr ov_genai_whisper_generation_config = + config.handle.native() + +proc native(pipeline: LlmPipeline): ptr ov_genai_llm_pipeline = + pipeline.handle.native() + +proc native(pipeline: VlmPipeline): ptr ov_genai_vlm_pipeline = + pipeline.handle.native() + +proc native(pipeline: WhisperPipeline): ptr ov_genai_whisper_pipeline = + pipeline.handle.native() + +proc raiseGenAiError(operation: string; status: ov_status_e) {.noreturn.} = + var err = newException(GenAiError, + operation & " failed with GenAI/OpenVINO status " & $status) + err.operation = operation + err.status = cint(status) + raise err + +proc checkGenAiStatus(status: ov_status_e; operation: string) = + if status != 0: + raiseGenAiError(operation, status) + +proc checkJsonStatus(status: ov_genai_json_container_status_e; + operation: string) = + if status != OV_GENAI_JSON_CONTAINER_OK: + raiseGenAiError(operation, ov_status_e(status)) + +proc checkHistoryStatus(status: ov_genai_chat_history_status_e; + operation: string) = + if status != OV_GENAI_CHAT_HISTORY_OK: + raiseGenAiError(operation, ov_status_e(status)) + +proc newGenerationConfig*(): GenerationConfig = + ## Creates default text generation settings. + var nativeConfig: ptr ov_genai_generation_config = nil + checkGenAiStatus(ov_genai_generation_config_create(addr nativeConfig), + "create generation config") + result.handle = newHandle(nativeConfig, releaseGenerationConfig, + "GenAI generation config") + +proc generationConfigFromJson*(path: string): GenerationConfig = + ## Loads generation settings from a model-compatible JSON file. + checkCString(path, "generation config path") + var nativeConfig: ptr ov_genai_generation_config = nil + checkGenAiStatus(ov_genai_generation_config_create_from_json(path.cstring, + addr nativeConfig), "load generation config") + result.handle = newHandle(nativeConfig, releaseGenerationConfig, + "GenAI generation config") + +proc close*(config: GenerationConfig) = config.handle.close() +proc isClosed*(config: GenerationConfig): bool = config.handle.isClosed() + +proc setMaxNewTokens*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("maxNewTokens cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_max_new_tokens( + config.native(), csize_t(value)), "set maximum new tokens") + +proc maxNewTokens*(config: GenerationConfig): int = + var value: csize_t = 0 + checkGenAiStatus(ov_genai_generation_config_get_max_new_tokens( + config.native(), addr value), "get maximum new tokens") + result = int(value) + +proc setMaxLength*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("maxLength cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_max_length( + config.native(), csize_t(value)), "set maximum length") + +proc setMinNewTokens*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("minNewTokens cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_min_new_tokens( + config.native(), csize_t(value)), "set minimum new tokens") + +proc setIgnoreEos*(config: GenerationConfig; value: bool) = + checkGenAiStatus(ov_genai_generation_config_set_ignore_eos( + config.native(), value), "set ignore EOS") + +proc setEcho*(config: GenerationConfig; value: bool) = + checkGenAiStatus(ov_genai_generation_config_set_echo( + config.native(), value), "set echo") + +proc setLogprobs*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("logprobs cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_logprobs( + config.native(), csize_t(value)), "set logprobs") + +proc setStopStrings*(config: GenerationConfig; values: openArray[string]) = + var strings = newSeq[cstring](values.len) + for i, value in values: + checkCString(value, "GenAI stop string") + strings[i] = value.cstring + # invariant: the upstream implementation rejects a null `strings` pointer + # even when `count == 0`; this local sentinel is non-null and is not read. + var emptyString: cstring = nil + let data = if strings.len == 0: addr emptyString else: addr strings[0] + checkGenAiStatus(ov_genai_generation_config_set_stop_strings( + config.native(), data, csize_t(strings.len)), "set stop strings") + +proc setIncludeStopString*(config: GenerationConfig; value: bool) = + checkGenAiStatus(ov_genai_generation_config_set_include_stop_str_in_output( + config.native(), value), "set include stop string") + +proc setStopTokenIds*(config: GenerationConfig; values: openArray[int64]) = + let data = if values.len == 0: nil else: unsafeAddr values[0] + checkGenAiStatus(ov_genai_generation_config_set_stop_token_ids( + config.native(), data, csize_t(values.len)), "set stop token IDs") + +proc setNumBeamGroups*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("numBeamGroups cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_num_beam_groups( + config.native(), csize_t(value)), "set beam groups") + +proc setNumBeams*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("numBeams cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_num_beams( + config.native(), csize_t(value)), "set beams") + +proc setDiversityPenalty*(config: GenerationConfig; value: float32) = + checkGenAiStatus(ov_genai_generation_config_set_diversity_penalty( + config.native(), cfloat(value)), "set diversity penalty") + +proc setLengthPenalty*(config: GenerationConfig; value: float32) = + checkGenAiStatus(ov_genai_generation_config_set_length_penalty( + config.native(), cfloat(value)), "set length penalty") + +proc setNumReturnSequences*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("numReturnSequences cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_num_return_sequences( + config.native(), csize_t(value)), "set return sequences") + +proc setNoRepeatNgramSize*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("noRepeatNgramSize cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_no_repeat_ngram_size( + config.native(), csize_t(value)), "set no-repeat n-gram size") + +proc setStopCriteria*(config: GenerationConfig; value: StopCriteria) = + let rawValue = case value + of scEarly: rawGenAi.EARLY + of scHeuristic: rawGenAi.HEURISTIC + of scNever: rawGenAi.NEVER + checkGenAiStatus(ov_genai_generation_config_set_stop_criteria( + config.native(), rawValue), "set stop criteria") + +proc setTemperature*(config: GenerationConfig; value: float32) = + checkGenAiStatus(ov_genai_generation_config_set_temperature( + config.native(), cfloat(value)), "set temperature") + +proc setTopP*(config: GenerationConfig; value: float32) = + checkGenAiStatus(ov_genai_generation_config_set_top_p( + config.native(), cfloat(value)), "set top-p") + +proc setTopK*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("topK cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_top_k( + config.native(), csize_t(value)), "set top-k") + +proc setMinP*(config: GenerationConfig; value: float32) = + checkGenAiStatus(ov_genai_generation_config_set_min_p( + config.native(), cfloat(value)), "set min-p") + +proc setDoSample*(config: GenerationConfig; value: bool) = + checkGenAiStatus(ov_genai_generation_config_set_do_sample( + config.native(), value), "set sampling") + +proc setRepetitionPenalty*(config: GenerationConfig; value: float32) = + checkGenAiStatus(ov_genai_generation_config_set_repetition_penalty( + config.native(), cfloat(value)), "set repetition penalty") + +proc setPresencePenalty*(config: GenerationConfig; value: float32) = + checkGenAiStatus(ov_genai_generation_config_set_presence_penalty( + config.native(), cfloat(value)), "set presence penalty") + +proc setFrequencyPenalty*(config: GenerationConfig; value: float32) = + checkGenAiStatus(ov_genai_generation_config_set_frequency_penalty( + config.native(), cfloat(value)), "set frequency penalty") + +proc setRngSeed*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("rngSeed cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_rng_seed( + config.native(), csize_t(value)), "set RNG seed") + +proc setAssistantConfidenceThreshold*(config: GenerationConfig; + value: float32) = + checkGenAiStatus(ov_genai_generation_config_set_assistant_confidence_threshold( + config.native(), cfloat(value)), "set assistant confidence threshold") + +proc setNumAssistantTokens*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("numAssistantTokens cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_num_assistant_tokens( + config.native(), csize_t(value)), "set assistant tokens") + +proc setMaxNgramSize*(config: GenerationConfig; value: int) = + if value < 0: raiseArgumentError("maxNgramSize cannot be negative") + checkGenAiStatus(ov_genai_generation_config_set_max_ngram_size( + config.native(), csize_t(value)), "set maximum n-gram size") + +proc setEosTokenId*(config: GenerationConfig; value: int64) = + checkGenAiStatus(ov_genai_generation_config_set_eos_token_id( + config.native(), value), "set EOS token ID") + +proc validate*(config: GenerationConfig) = + checkGenAiStatus(ov_genai_generation_config_validate(config.native()), + "validate generation config") + +proc newJsonContainer*(): JsonContainer = + var nativeJson: ptr ov_genai_json_container = nil + checkJsonStatus(ov_genai_json_container_create(addr nativeJson), + "create JSON container") + result.handle = newHandle(nativeJson, releaseJsonContainer, + "GenAI JSON container") + +proc newJsonObject*(): JsonContainer = + var nativeJson: ptr ov_genai_json_container = nil + checkJsonStatus(ov_genai_json_container_create_object(addr nativeJson), + "create JSON object") + result.handle = newHandle(nativeJson, releaseJsonContainer, + "GenAI JSON container") + +proc newJsonArray*(): JsonContainer = + var nativeJson: ptr ov_genai_json_container = nil + checkJsonStatus(ov_genai_json_container_create_array(addr nativeJson), + "create JSON array") + result.handle = newHandle(nativeJson, releaseJsonContainer, + "GenAI JSON container") + +proc jsonFromString*(value: string): JsonContainer = + checkCString(value, "GenAI JSON string") + var nativeJson: ptr ov_genai_json_container = nil + checkJsonStatus(ov_genai_json_container_create_from_json_string( + addr nativeJson, value.cstring), "parse JSON") + result.handle = newHandle(nativeJson, releaseJsonContainer, + "GenAI JSON container") + +proc close*(json: JsonContainer) = json.handle.close() +proc isClosed*(json: JsonContainer): bool = json.handle.isClosed() + +proc toJson*(json: JsonContainer): string = + var size: csize_t = 0 + checkJsonStatus(ov_genai_json_container_to_json_string( + json.native(), nil, addr size), "measure JSON string") + if size == 0: return "" + result = newString(int(size)) + checkJsonStatus(ov_genai_json_container_to_json_string( + json.native(), result.cstring, addr size), "copy JSON string") + result.setLen(int(size) - 1) + +proc copy*(json: JsonContainer): JsonContainer = + var copied: ptr ov_genai_json_container = nil + checkJsonStatus(ov_genai_json_container_copy(json.native(), addr copied), + "copy JSON container") + result.handle = newHandle(copied, releaseJsonContainer, + "GenAI JSON container") + +proc newChatHistory*(): ChatHistory = + var nativeHistory: ptr ov_genai_chat_history = nil + checkHistoryStatus(ov_genai_chat_history_create(addr nativeHistory), + "create chat history") + result.handle = newHandle(nativeHistory, releaseChatHistory, + "GenAI chat history") + +proc chatHistoryFromJson*(messages: JsonContainer): ChatHistory = + var nativeHistory: ptr ov_genai_chat_history = nil + checkHistoryStatus(ov_genai_chat_history_create_from_json_container( + addr nativeHistory, messages.native()), "create chat history from JSON") + result.handle = newHandle(nativeHistory, releaseChatHistory, + "GenAI chat history") + +proc close*(history: ChatHistory) = history.handle.close() +proc isClosed*(history: ChatHistory): bool = history.handle.isClosed() + +proc len*(history: ChatHistory): int = + var size: csize_t = 0 + checkHistoryStatus(ov_genai_chat_history_size(history.native(), addr size), + "get chat history size") + result = int(size) + +proc isEmpty*(history: ChatHistory): bool = + var empty: cint = 0 + checkHistoryStatus(ov_genai_chat_history_empty(history.native(), addr empty), + "check chat history") + result = empty != 0 + +proc clear*(history: ChatHistory) = + checkHistoryStatus(ov_genai_chat_history_clear(history.native()), + "clear chat history") + +proc pushBack*(history: ChatHistory; message: JsonContainer) = + checkHistoryStatus(ov_genai_chat_history_push_back(history.native(), + message.native()), "append chat message") + +proc popBack*(history: ChatHistory) = + checkHistoryStatus(ov_genai_chat_history_pop_back(history.native()), + "remove last chat message") + +proc wrapJson(nativeJson: ptr ov_genai_json_container): JsonContainer = + result.handle = newHandle(nativeJson, releaseJsonContainer, + "GenAI JSON container") + +proc messages*(history: ChatHistory): JsonContainer = + var nativeJson: ptr ov_genai_json_container = nil + checkHistoryStatus(ov_genai_chat_history_get_messages(history.native(), + addr nativeJson), "get chat messages") + result = wrapJson(nativeJson) + +proc messageAt*(history: ChatHistory; index: int): JsonContainer = + if index < 0: raiseArgumentError("chat history index cannot be negative") + var nativeJson: ptr ov_genai_json_container = nil + checkHistoryStatus(ov_genai_chat_history_get_message(history.native(), + csize_t(index), addr nativeJson), "get chat message") + result = wrapJson(nativeJson) + +proc firstMessage*(history: ChatHistory): JsonContainer = + var nativeJson: ptr ov_genai_json_container = nil + checkHistoryStatus(ov_genai_chat_history_get_first(history.native(), + addr nativeJson), "get first chat message") + result = wrapJson(nativeJson) + +proc lastMessage*(history: ChatHistory): JsonContainer = + var nativeJson: ptr ov_genai_json_container = nil + checkHistoryStatus(ov_genai_chat_history_get_last(history.native(), + addr nativeJson), "get last chat message") + result = wrapJson(nativeJson) + +proc setTools*(history: ChatHistory; tools: JsonContainer) = + checkHistoryStatus(ov_genai_chat_history_set_tools(history.native(), + tools.native()), "set chat tools") + +proc tools*(history: ChatHistory): JsonContainer = + var nativeJson: ptr ov_genai_json_container = nil + checkHistoryStatus(ov_genai_chat_history_get_tools(history.native(), + addr nativeJson), "get chat tools") + result = wrapJson(nativeJson) + +proc setExtraContext*(history: ChatHistory; context: JsonContainer) = + checkHistoryStatus(ov_genai_chat_history_set_extra_context(history.native(), + context.native()), "set chat extra context") + +proc extraContext*(history: ChatHistory): JsonContainer = + var nativeJson: ptr ov_genai_json_container = nil + checkHistoryStatus(ov_genai_chat_history_get_extra_context(history.native(), + addr nativeJson), "get chat extra context") + result = wrapJson(nativeJson) + +proc readSizedString(sizeCall, fillCall: proc (buffer: cstring; + size: ptr csize_t): ov_status_e {.closure.}; operation: string): string = + var size: csize_t = 0 + checkGenAiStatus(sizeCall(nil, addr size), "measure " & operation) + if size == 0: return "" + result = newString(int(size)) + checkGenAiStatus(fillCall(result.cstring, addr size), "read " & operation) + result.setLen(int(size) - 1) + +proc text*(results: DecodedResults): string = + readSizedString( + proc (buffer: cstring; size: ptr csize_t): ov_status_e = + ov_genai_decoded_results_get_string(results.native(), buffer, size), + proc (buffer: cstring; size: ptr csize_t): ov_status_e = + ov_genai_decoded_results_get_string(results.native(), buffer, size), + "generated text") + +proc close*(results: DecodedResults) = results.handle.close() +proc isClosed*(results: DecodedResults): bool = results.handle.isClosed() + +proc generationMetrics*(results: DecodedResults): PerfMetrics = + var nativeMetrics: ptr ov_genai_perf_metrics = nil + checkGenAiStatus(ov_genai_decoded_results_get_perf_metrics( + results.native(), addr nativeMetrics), "get generation metrics") + result.handle = newHandle(nativeMetrics, releasePerfMetrics, + "GenAI performance metrics") + +proc validatePipelineInputs(modelPath, device: string; + properties: openArray[(string, string)]) = + if properties.len > 16: + raiseArgumentError("GenAI pipeline constructors accept at most 16 " & + "property pairs through this adapter") + checkCString(modelPath, "GenAI model path") + checkCString(device, "GenAI device") + for property in properties: + checkCString(property[0], "GenAI property key") + checkCString(property[1], "GenAI property value") + +proc newLlmPipeline*(modelPath: string; device = "CPU"; + properties: seq[(string, string)] = @[]): LlmPipeline = + ## Creates a text generation pipeline. Property values are passed as strings. + validatePipelineInputs(modelPath, device, properties) + var nativePipeline: ptr ov_genai_llm_pipeline = nil + let status = createGenAiPipeline( + rawGenAi.genAiFunctionSymbol("ov_genai_llm_pipeline_create"), modelPath, + device, properties, addr nativePipeline) + checkGenAiStatus(status, "create LLM pipeline") + result.handle = newHandle(nativePipeline, releaseLlmPipeline, + "GenAI LLM pipeline") + +proc close*(pipeline: LlmPipeline) = pipeline.handle.close() +proc isClosed*(pipeline: LlmPipeline): bool = pipeline.handle.isClosed() + +proc optionalConfig(config: GenerationConfig): ptr ov_genai_generation_config = + if config.handle == nil: nil else: config.native() + +proc generate*(pipeline: LlmPipeline; prompt: string; + config = GenerationConfig()): DecodedResults = + ## Generates one response, blocking the calling thread until it completes. + checkCString(prompt, "GenAI prompt") + var nativeResults: ptr ov_genai_decoded_results = nil + checkGenAiStatus(ov_genai_llm_pipeline_generate(pipeline.native(), + prompt.cstring, optionalConfig(config), nil, addr nativeResults), + "generate text") + result.handle = newHandle(nativeResults, releaseDecodedResults, + "GenAI decoded results") + +proc generate*(pipeline: LlmPipeline; history: ChatHistory; + config = GenerationConfig()): DecodedResults = + ## Generates from a structured chat history. + var nativeResults: ptr ov_genai_decoded_results = nil + checkGenAiStatus(ov_genai_llm_pipeline_generate_with_history( + pipeline.native(), history.native(), optionalConfig(config), nil, + addr nativeResults), "generate from chat history") + result.handle = newHandle(nativeResults, releaseDecodedResults, + "GenAI decoded results") + +proc invokeStream(text: cstring; args: pointer): ov_genai_streaming_status_e + {.cdecl, raises: [].} +proc raiseStreamCallbackError(context: StreamContext) {.noreturn.} + +proc streamGenerate*(pipeline: LlmPipeline; history: ChatHistory; + handler: StreamHandler; + config = GenerationConfig()): string = + ## Streams a response generated from structured chat history. + if handler == nil: + raiseArgumentError("stream handler cannot be nil") + var context = StreamContext(handler: handler) + var callback = ov_genai_streamer_callback(callbackFunc: invokeStream, + args: addr context) + let status = ov_genai_llm_pipeline_generate_with_history( + pipeline.native(), history.native(), optionalConfig(config), addr callback, + nil) + if context.callbackFailed: + raiseStreamCallbackError(context) + checkGenAiStatus(status, "stream generation from chat history") + result = context.accumulated + +proc startChat*(pipeline: LlmPipeline) = + checkGenAiStatus(ov_genai_llm_pipeline_start_chat(pipeline.native()), + "start LLM chat") + +proc finishChat*(pipeline: LlmPipeline) = + checkGenAiStatus(ov_genai_llm_pipeline_finish_chat(pipeline.native()), + "finish LLM chat") + +proc generationConfig*(pipeline: LlmPipeline): GenerationConfig = + var nativeConfig: ptr ov_genai_generation_config = nil + checkGenAiStatus(ov_genai_llm_pipeline_get_generation_config( + pipeline.native(), addr nativeConfig), "get LLM generation config") + result.handle = newHandle(nativeConfig, releaseGenerationConfig, + "GenAI generation config") + +proc setGenerationConfig*(pipeline: LlmPipeline; config: GenerationConfig) = + checkGenAiStatus(ov_genai_llm_pipeline_set_generation_config( + pipeline.native(), config.native()), "set LLM generation config") + +proc invokeStream(text: cstring; args: pointer): ov_genai_streaming_status_e + {.cdecl, raises: [].} = + # invariant: `args` points to StreamContext on the still-active generate call + # stack; GenAI invokes this callback synchronously before that call returns. + let context = cast[ptr StreamContext](args) + if context.callbackFailed: + return OV_GENAI_STREAMING_STATUS_STOP + try: + case context.handler($text) + of streamContinue: + context.accumulated.add($text) + result = OV_GENAI_STREAMING_STATUS_RUNNING + of streamStop: + context.accumulated.add($text) + result = OV_GENAI_STREAMING_STATUS_STOP + of streamCancel: + context.accumulated.add($text) + result = OV_GENAI_STREAMING_STATUS_CANCEL + except CatchableError as error: + context.callbackFailed = true + context.failureMessage = error.msg + result = OV_GENAI_STREAMING_STATUS_STOP + +proc raiseStreamCallbackError(context: StreamContext) {.noreturn.} = + var err = newException(GenAiCallbackError, + "GenAI streaming callback raised: " & context.failureMessage) + err.callbackMessage = context.failureMessage + raise err + +proc streamGenerate*(pipeline: LlmPipeline; prompt: string; + handler: StreamHandler; + config = GenerationConfig()): string = + ## Streams decoded pieces synchronously and also returns their concatenation. + ## A callback exception is re-raised only after the native call has returned. + if handler == nil: + raiseArgumentError("stream handler cannot be nil") + checkCString(prompt, "GenAI prompt") + var context = StreamContext(handler: handler) + var callback = ov_genai_streamer_callback(callbackFunc: invokeStream, + args: addr context) + let status = ov_genai_llm_pipeline_generate(pipeline.native(), + prompt.cstring, optionalConfig(config), addr callback, nil) + if context.callbackFailed: + raiseStreamCallbackError(context) + checkGenAiStatus(status, "stream text generation") + result = context.accumulated + +proc newVlmPipeline*(modelPath: string; device = "CPU"; + properties: seq[(string, string)] = @[]): VlmPipeline = + ## Creates a visual-language pipeline. Supply image tensors to `generate`. + validatePipelineInputs(modelPath, device, properties) + var nativePipeline: ptr ov_genai_vlm_pipeline = nil + let status = createGenAiPipeline( + rawGenAi.genAiFunctionSymbol("ov_genai_vlm_pipeline_create"), modelPath, + device, properties, addr nativePipeline) + checkGenAiStatus(status, "create VLM pipeline") + result.handle = newHandle(nativePipeline, releaseVlmPipeline, + "GenAI VLM pipeline") + +proc close*(pipeline: VlmPipeline) = pipeline.handle.close() +proc isClosed*(pipeline: VlmPipeline): bool = pipeline.handle.isClosed() + +proc generate*(pipeline: VlmPipeline; prompt: string; + images: openArray[Tensor]; + config = GenerationConfig()): VlmDecodedResults = + ## Generates from text and zero or more OpenVINO image tensors. + checkCString(prompt, "GenAI prompt") + var rawImages = newSeq[ptr ov_tensor_t](images.len) + for i, image in images: + rawImages[i] = image.unsafeNativeHandle() + let imagePointer = if rawImages.len == 0: nil else: addr rawImages[0] + var nativeResults: ptr ov_genai_vlm_decoded_results = nil + checkGenAiStatus(ov_genai_vlm_pipeline_generate(pipeline.native(), + prompt.cstring, imagePointer, csize_t(rawImages.len), + optionalConfig(config), nil, addr nativeResults), "generate visual text") + result.handle = newHandle(nativeResults, releaseVlmResults, + "GenAI VLM decoded results") + +proc generate*(pipeline: VlmPipeline; history: ChatHistory; + images: openArray[Tensor]; + config = GenerationConfig()): VlmDecodedResults = + ## Generates from structured chat messages and images for the latest message. + var rawImages = newSeq[ptr ov_tensor_t](images.len) + for i, image in images: + rawImages[i] = image.unsafeNativeHandle() + let imagePointer = if rawImages.len == 0: nil else: addr rawImages[0] + var nativeResults: ptr ov_genai_vlm_decoded_results = nil + checkGenAiStatus(ov_genai_vlm_pipeline_generate_with_history( + pipeline.native(), history.native(), imagePointer, csize_t(rawImages.len), + optionalConfig(config), nil, addr nativeResults), + "generate visual response from chat history") + result.handle = newHandle(nativeResults, releaseVlmResults, + "GenAI VLM decoded results") + +proc streamGenerate*(pipeline: VlmPipeline; prompt: string; + images: openArray[Tensor]; handler: StreamHandler; + config = GenerationConfig()): string = + ## Streams a VLM response synchronously and returns all emitted pieces. + if handler == nil: + raiseArgumentError("stream handler cannot be nil") + checkCString(prompt, "GenAI prompt") + var rawImages = newSeq[ptr ov_tensor_t](images.len) + for i, image in images: + rawImages[i] = image.unsafeNativeHandle() + let imagePointer = if rawImages.len == 0: nil else: addr rawImages[0] + var context = StreamContext(handler: handler) + var callback = ov_genai_streamer_callback(callbackFunc: invokeStream, + args: addr context) + let status = ov_genai_vlm_pipeline_generate(pipeline.native(), + prompt.cstring, imagePointer, csize_t(rawImages.len), + optionalConfig(config), addr callback, nil) + if context.callbackFailed: + raiseStreamCallbackError(context) + checkGenAiStatus(status, "stream VLM generation") + result = context.accumulated + +proc streamGenerate*(pipeline: VlmPipeline; history: ChatHistory; + images: openArray[Tensor]; handler: StreamHandler; + config = GenerationConfig()): string = + ## Streams a VLM response from structured history and image tensors. + if handler == nil: + raiseArgumentError("stream handler cannot be nil") + var rawImages = newSeq[ptr ov_tensor_t](images.len) + for i, image in images: + rawImages[i] = image.unsafeNativeHandle() + let imagePointer = if rawImages.len == 0: nil else: addr rawImages[0] + var context = StreamContext(handler: handler) + var callback = ov_genai_streamer_callback(callbackFunc: invokeStream, + args: addr context) + let status = ov_genai_vlm_pipeline_generate_with_history( + pipeline.native(), history.native(), imagePointer, csize_t(rawImages.len), + optionalConfig(config), addr callback, nil) + if context.callbackFailed: + raiseStreamCallbackError(context) + checkGenAiStatus(status, "stream VLM generation from chat history") + result = context.accumulated + +proc startChat*(pipeline: VlmPipeline) = + checkGenAiStatus(ov_genai_vlm_pipeline_start_chat(pipeline.native()), + "start VLM chat") + +proc finishChat*(pipeline: VlmPipeline) = + checkGenAiStatus(ov_genai_vlm_pipeline_finish_chat(pipeline.native()), + "finish VLM chat") + +proc generationConfig*(pipeline: VlmPipeline): GenerationConfig = + var nativeConfig: ptr ov_genai_generation_config = nil + checkGenAiStatus(ov_genai_vlm_pipeline_get_generation_config( + pipeline.native(), addr nativeConfig), "get VLM generation config") + result.handle = newHandle(nativeConfig, releaseGenerationConfig, + "GenAI generation config") + +proc setGenerationConfig*(pipeline: VlmPipeline; config: GenerationConfig) = + checkGenAiStatus(ov_genai_vlm_pipeline_set_generation_config( + pipeline.native(), config.native()), "set VLM generation config") + +proc text*(results: VlmDecodedResults): string = + var size: csize_t = 0 + checkGenAiStatus(ov_genai_vlm_decoded_results_get_string( + results.handle.native(), nil, addr size), "measure VLM result") + if size == 0: return "" + result = newString(int(size)) + checkGenAiStatus(ov_genai_vlm_decoded_results_get_string( + results.handle.native(), result.cstring, addr size), "read VLM result") + result.setLen(int(size) - 1) + +proc close*(results: VlmDecodedResults) = results.handle.close() + +proc generationMetrics*(results: VlmDecodedResults): PerfMetrics = + var nativeMetrics: ptr ov_genai_perf_metrics = nil + checkGenAiStatus(ov_genai_vlm_decoded_results_get_perf_metrics( + results.handle.native(), addr nativeMetrics), "get VLM performance metrics") + result.handle = newHandle(nativeMetrics, releasePerfMetrics, + "GenAI performance metrics") + +proc newWhisperPipeline*(modelPath: string; device = "CPU"; + properties: seq[(string, string)] = @[]): WhisperPipeline = + ## Creates a Whisper pipeline. Audio input is expected as mono 16 kHz float32. + validatePipelineInputs(modelPath, device, properties) + var nativePipeline: ptr ov_genai_whisper_pipeline = nil + let status = createGenAiPipeline( + rawGenAi.genAiFunctionSymbol("ov_genai_whisper_pipeline_create"), modelPath, + device, properties, addr nativePipeline) + checkGenAiStatus(status, "create Whisper pipeline") + result.handle = newHandle(nativePipeline, releaseWhisperPipeline, + "GenAI Whisper pipeline") + +proc close*(pipeline: WhisperPipeline) = pipeline.handle.close() +proc isClosed*(pipeline: WhisperPipeline): bool = pipeline.handle.isClosed() + +proc generationConfig*(pipeline: WhisperPipeline): WhisperGenerationConfig = + var nativeConfig: ptr ov_genai_whisper_generation_config = nil + checkGenAiStatus(ov_genai_whisper_pipeline_get_generation_config( + pipeline.native(), addr nativeConfig), "get Whisper generation config") + result.handle = newHandle(nativeConfig, releaseWhisperConfig, + "GenAI Whisper config") + +proc setGenerationConfig*(pipeline: WhisperPipeline; + config: WhisperGenerationConfig) = + checkGenAiStatus(ov_genai_whisper_pipeline_set_generation_config( + pipeline.native(), config.native()), "set Whisper generation config") + +proc newWhisperGenerationConfig*(): WhisperGenerationConfig = + var nativeConfig: ptr ov_genai_whisper_generation_config = nil + checkGenAiStatus(ov_genai_whisper_generation_config_create(addr nativeConfig), + "create Whisper config") + result.handle = newHandle(nativeConfig, releaseWhisperConfig, + "GenAI Whisper config") + +proc whisperGenerationConfigFromJson*(path: string): WhisperGenerationConfig = + checkCString(path, "Whisper config path") + var nativeConfig: ptr ov_genai_whisper_generation_config = nil + checkGenAiStatus(ov_genai_whisper_generation_config_create_from_json( + path.cstring, addr nativeConfig), "load Whisper generation config") + result.handle = newHandle(nativeConfig, releaseWhisperConfig, + "GenAI Whisper config") + +proc close*(config: WhisperGenerationConfig) = config.handle.close() +proc validate*(config: WhisperGenerationConfig) = + checkGenAiStatus(ov_genai_whisper_generation_config_validate(config.native()), + "validate Whisper config") + +proc setLanguage*(config: WhisperGenerationConfig; language: string) = + checkCString(language, "Whisper language") + checkGenAiStatus(ov_genai_whisper_generation_config_set_language( + config.native(), language.cstring), "set Whisper language") + +proc setTask*(config: WhisperGenerationConfig; task: string) = + checkCString(task, "Whisper task") + checkGenAiStatus(ov_genai_whisper_generation_config_set_task( + config.native(), task.cstring), "set Whisper task") + +proc setReturnTimestamps*(config: WhisperGenerationConfig; value: bool) = + checkGenAiStatus(ov_genai_whisper_generation_config_set_return_timestamps( + config.native(), value), "set Whisper timestamps") + +proc setInitialPrompt*(config: WhisperGenerationConfig; prompt: string) = + checkCString(prompt, "Whisper initial prompt") + checkGenAiStatus(ov_genai_whisper_generation_config_set_initial_prompt( + config.native(), prompt.cstring), "set Whisper initial prompt") + +proc setHotwords*(config: WhisperGenerationConfig; words: string) = + checkCString(words, "Whisper hotwords") + checkGenAiStatus(ov_genai_whisper_generation_config_set_hotwords( + config.native(), words.cstring), "set Whisper hotwords") + +proc setIsMultilingual*(config: WhisperGenerationConfig; value: bool) = + checkGenAiStatus(ov_genai_whisper_generation_config_set_is_multilingual( + config.native(), value), "set Whisper multilingual flag") + +proc setPreviousStartTokenId*(config: WhisperGenerationConfig; value: int64) = + checkGenAiStatus(ov_genai_whisper_generation_config_set_prev_sot_token_id( + config.native(), value), "set Whisper previous start token") + +proc setNoTimestampsTokenId*(config: WhisperGenerationConfig; value: int64) = + checkGenAiStatus(ov_genai_whisper_generation_config_set_no_timestamps_token_id( + config.native(), value), "set Whisper no-timestamps token") + +proc setMaxInitialTimestampIndex*(config: WhisperGenerationConfig; value: int) = + if value < 0: + raiseArgumentError("maxInitialTimestampIndex cannot be negative") + checkGenAiStatus(ov_genai_whisper_generation_config_set_max_initial_timestamp_index( + config.native(), csize_t(value)), "set Whisper maximum initial timestamp") + +proc setBeginSuppressTokens*(config: WhisperGenerationConfig; + values: openArray[int64]) = + let data = if values.len == 0: nil else: unsafeAddr values[0] + checkGenAiStatus(ov_genai_whisper_generation_config_set_begin_suppress_tokens( + config.native(), data, csize_t(values.len)), + "set Whisper begin-suppress tokens") + +proc setSuppressTokens*(config: WhisperGenerationConfig; + values: openArray[int64]) = + let data = if values.len == 0: nil else: unsafeAddr values[0] + checkGenAiStatus(ov_genai_whisper_generation_config_set_suppress_tokens( + config.native(), data, csize_t(values.len)), "set Whisper suppress tokens") + +proc whisperTokenIds(config: WhisperGenerationConfig; + countGetter: proc (native: ptr ov_genai_whisper_generation_config; + count: ptr csize_t): ov_status_e {.closure.}; + valueGetter: proc (native: ptr ov_genai_whisper_generation_config; + values: ptr int64; count: csize_t): ov_status_e + {.closure.}; + operation: string): seq[int64] = + var count: csize_t = 0 + checkGenAiStatus(countGetter(config.native(), addr count), + "get " & operation & " count") + result = newSeq[int64](int(count)) + if count > 0: + checkGenAiStatus(valueGetter(config.native(), addr result[0], count), + "get " & operation) + +proc beginSuppressTokens*(config: WhisperGenerationConfig): seq[int64] = + whisperTokenIds(config, + proc (native: ptr ov_genai_whisper_generation_config; + count: ptr csize_t): ov_status_e = + ov_genai_whisper_generation_config_get_begin_suppress_tokens_count( + native, count), + proc (native: ptr ov_genai_whisper_generation_config; values: ptr int64; + count: csize_t): ov_status_e = + ov_genai_whisper_generation_config_get_begin_suppress_tokens( + native, values, count), + "Whisper begin-suppress tokens") + +proc suppressTokens*(config: WhisperGenerationConfig): seq[int64] = + whisperTokenIds(config, + proc (native: ptr ov_genai_whisper_generation_config; + count: ptr csize_t): ov_status_e = + ov_genai_whisper_generation_config_get_suppress_tokens_count(native, + count), + proc (native: ptr ov_genai_whisper_generation_config; values: ptr int64; + count: csize_t): ov_status_e = + ov_genai_whisper_generation_config_get_suppress_tokens(native, values, + count), + "Whisper suppress tokens") + +proc whisperConfigString(config: WhisperGenerationConfig; + getter: proc (native: ptr ov_genai_whisper_generation_config; + buffer: cstring; size: ptr csize_t): ov_status_e {.closure.}; + operation: string): string = + var size: csize_t = 0 + checkGenAiStatus(getter(config.native(), nil, addr size), + "measure " & operation) + if size == 0: return "" + result = newString(int(size)) + checkGenAiStatus(getter(config.native(), result.cstring, addr size), + "read " & operation) + result.setLen(int(size) - 1) + +proc language*(config: WhisperGenerationConfig): string = + whisperConfigString(config, + proc (native: ptr ov_genai_whisper_generation_config; buffer: cstring; + size: ptr csize_t): ov_status_e = + ov_genai_whisper_generation_config_get_language(native, buffer, size), + "Whisper language") + +proc task*(config: WhisperGenerationConfig): string = + whisperConfigString(config, + proc (native: ptr ov_genai_whisper_generation_config; buffer: cstring; + size: ptr csize_t): ov_status_e = + ov_genai_whisper_generation_config_get_task(native, buffer, size), + "Whisper task") + +proc initialPrompt*(config: WhisperGenerationConfig): string = + whisperConfigString(config, + proc (native: ptr ov_genai_whisper_generation_config; buffer: cstring; + size: ptr csize_t): ov_status_e = + ov_genai_whisper_generation_config_get_initial_prompt(native, buffer, + size), + "Whisper initial prompt") + +proc hotwords*(config: WhisperGenerationConfig): string = + whisperConfigString(config, + proc (native: ptr ov_genai_whisper_generation_config; buffer: cstring; + size: ptr csize_t): ov_status_e = + ov_genai_whisper_generation_config_get_hotwords(native, buffer, size), + "Whisper hotwords") + +proc multilingual*(config: WhisperGenerationConfig): bool = + var value = false + checkGenAiStatus(ov_genai_whisper_generation_config_get_is_multilingual( + config.native(), addr value), "get Whisper multilingual flag") + result = value + +proc returnTimestamps*(config: WhisperGenerationConfig): bool = + var value = false + checkGenAiStatus(ov_genai_whisper_generation_config_get_return_timestamps( + config.native(), addr value), "get Whisper timestamp setting") + result = value + +proc tokenId(config: WhisperGenerationConfig; + getter: proc (native: ptr ov_genai_whisper_generation_config; + value: ptr int64): ov_status_e {.closure.}; + operation: string): int64 = + checkGenAiStatus(getter(config.native(), addr result), operation) + +proc decoderStartTokenId*(config: WhisperGenerationConfig): int64 = + tokenId(config, + proc (native: ptr ov_genai_whisper_generation_config; + value: ptr int64): ov_status_e = + ov_genai_whisper_generation_config_get_decoder_start_token_id(native, + value), + "get Whisper decoder start token") + +proc padTokenId*(config: WhisperGenerationConfig): int64 = + tokenId(config, + proc (native: ptr ov_genai_whisper_generation_config; + value: ptr int64): ov_status_e = + ov_genai_whisper_generation_config_get_pad_token_id(native, value), + "get Whisper pad token") + +proc translateTokenId*(config: WhisperGenerationConfig): int64 = + tokenId(config, + proc (native: ptr ov_genai_whisper_generation_config; + value: ptr int64): ov_status_e = + ov_genai_whisper_generation_config_get_translate_token_id(native, value), + "get Whisper translate token") + +proc transcribeTokenId*(config: WhisperGenerationConfig): int64 = + tokenId(config, + proc (native: ptr ov_genai_whisper_generation_config; + value: ptr int64): ov_status_e = + ov_genai_whisper_generation_config_get_transcribe_token_id(native, value), + "get Whisper transcribe token") + +proc previousStartTokenId*(config: WhisperGenerationConfig): int64 = + tokenId(config, + proc (native: ptr ov_genai_whisper_generation_config; + value: ptr int64): ov_status_e = + ov_genai_whisper_generation_config_get_prev_sot_token_id(native, value), + "get Whisper previous start token") + +proc noTimestampsTokenId*(config: WhisperGenerationConfig): int64 = + tokenId(config, + proc (native: ptr ov_genai_whisper_generation_config; + value: ptr int64): ov_status_e = + ov_genai_whisper_generation_config_get_no_timestamps_token_id(native, + value), + "get Whisper no-timestamps token") + +proc maxInitialTimestampIndex*(config: WhisperGenerationConfig): int = + var value: csize_t = 0 + checkGenAiStatus(ov_genai_whisper_generation_config_get_max_initial_timestamp_index( + config.native(), addr value), "get Whisper maximum initial timestamp") + result = int(value) + +proc generationConfig*(config: WhisperGenerationConfig): GenerationConfig = + var nativeConfig: ptr ov_genai_generation_config = nil + checkGenAiStatus(ov_genai_whisper_generation_config_get_generation_config( + config.native(), addr nativeConfig), "get Whisper token generation config") + result.handle = newHandle(nativeConfig, releaseGenerationConfig, + "GenAI generation config") + + +proc setDecoderStartTokenId*(config: WhisperGenerationConfig; value: int64) = + checkGenAiStatus(ov_genai_whisper_generation_config_set_decoder_start_token_id( + config.native(), value), "set Whisper decoder start token") + +proc setPadTokenId*(config: WhisperGenerationConfig; value: int64) = + checkGenAiStatus(ov_genai_whisper_generation_config_set_pad_token_id( + config.native(), value), "set Whisper pad token") + +proc setTranslateTokenId*(config: WhisperGenerationConfig; value: int64) = + checkGenAiStatus(ov_genai_whisper_generation_config_set_translate_token_id( + config.native(), value), "set Whisper translate token") + +proc setTranscribeTokenId*(config: WhisperGenerationConfig; value: int64) = + checkGenAiStatus(ov_genai_whisper_generation_config_set_transcribe_token_id( + config.native(), value), "set Whisper transcribe token") + +proc optionalWhisperConfig(config: WhisperGenerationConfig): + ptr ov_genai_whisper_generation_config = + if config.handle == nil: nil else: config.native() + +proc transcribe*(pipeline: WhisperPipeline; audio: openArray[float32]; + config = WhisperGenerationConfig()): WhisperDecodedResults = + ## Recognizes audio supplied as mono 16 kHz float32 samples. + if audio.len == 0: + raiseArgumentError("audio input must contain at least one sample") + let rawAudio = if audio.len == 0: nil else: unsafeAddr audio[0] + var nativeResults: ptr ov_genai_whisper_decoded_results = nil + checkGenAiStatus(ov_genai_whisper_pipeline_generate(pipeline.native(), + rawAudio, csize_t(audio.len), optionalWhisperConfig(config), + addr nativeResults), "transcribe audio") + result.handle = newHandle(nativeResults, releaseWhisperResults, + "GenAI Whisper decoded results") + +proc close*(results: WhisperDecodedResults) = results.handle.close() + +proc text*(results: WhisperDecodedResults): string = + readSizedString( + proc (buffer: cstring; size: ptr csize_t): ov_status_e = + ov_genai_whisper_decoded_results_get_string(results.handle.native(), + buffer, size), + proc (buffer: cstring; size: ptr csize_t): ov_status_e = + ov_genai_whisper_decoded_results_get_string(results.handle.native(), + buffer, size), + "Whisper result") + +proc transcriptionCount*(results: WhisperDecodedResults): int = + var count: csize_t = 0 + checkGenAiStatus(ov_genai_whisper_decoded_results_get_texts_count( + results.handle.native(), addr count), "get transcription count") + result = int(count) + +proc transcription*(results: WhisperDecodedResults; index = 0): string = + if index < 0: raiseArgumentError("transcription index cannot be negative") + var size: csize_t = 0 + checkGenAiStatus(ov_genai_whisper_decoded_results_get_text_at( + results.handle.native(), csize_t(index), nil, addr size), + "measure transcription") + if size == 0: return "" + result = newString(int(size)) + checkGenAiStatus(ov_genai_whisper_decoded_results_get_text_at( + results.handle.native(), csize_t(index), result.cstring, addr size), + "read transcription") + result.setLen(int(size) - 1) + +proc score*(results: WhisperDecodedResults; index = 0): float32 = + if index < 0: raiseArgumentError("transcription index cannot be negative") + var value: cfloat = 0 + checkGenAiStatus(ov_genai_whisper_decoded_results_get_score_at( + results.handle.native(), csize_t(index), addr value), "get transcription score") + result = float32(value) + +proc hasChunks*(results: WhisperDecodedResults): bool = + var value = false + checkGenAiStatus(ov_genai_whisper_decoded_results_has_chunks( + results.handle.native(), addr value), "check transcription chunks") + result = value + +proc chunkCount*(results: WhisperDecodedResults): int = + var count: csize_t = 0 + checkGenAiStatus(ov_genai_whisper_decoded_results_get_chunks_count( + results.handle.native(), addr count), "get transcription chunk count") + result = int(count) + +proc chunkAt*(results: WhisperDecodedResults; index: int): WhisperChunk = + if index < 0: raiseArgumentError("transcription chunk index cannot be negative") + var nativeChunk: ptr ov_genai_whisper_decoded_result_chunk = nil + checkGenAiStatus(ov_genai_whisper_decoded_results_get_chunk_at( + results.handle.native(), csize_t(index), addr nativeChunk), + "get transcription chunk") + result.handle = newHandle(nativeChunk, releaseWhisperChunk, + "GenAI Whisper chunk") + +proc close*(chunk: WhisperChunk) = chunk.handle.close() + +proc chunkText*(chunk: WhisperChunk): string = + var size: csize_t = 0 + checkGenAiStatus(ov_genai_whisper_decoded_result_chunk_get_text( + chunk.native(), nil, addr size), "measure transcription chunk") + if size == 0: return "" + result = newString(int(size)) + checkGenAiStatus(ov_genai_whisper_decoded_result_chunk_get_text( + chunk.native(), result.cstring, addr size), "read transcription chunk") + result.setLen(int(size) - 1) + +proc chunkTimestamps*(chunk: WhisperChunk): tuple[startTime, endTime: float32] = + var startTime, endTime: cfloat = 0 + checkGenAiStatus(ov_genai_whisper_decoded_result_chunk_get_start_ts( + chunk.native(), addr startTime), "get chunk start time") + checkGenAiStatus(ov_genai_whisper_decoded_result_chunk_get_end_ts( + chunk.native(), addr endTime), "get chunk end time") + result = (float32(startTime), float32(endTime)) + +proc generationMetrics*(results: WhisperDecodedResults): PerfMetrics = + var nativeMetrics: ptr ov_genai_perf_metrics = nil + checkGenAiStatus(ov_genai_whisper_decoded_results_get_perf_metrics( + results.handle.native(), addr nativeMetrics), "get Whisper metrics") + result.handle = newHandle(nativeMetrics, releasePerfMetrics, + "GenAI performance metrics") + +proc close*(metrics: PerfMetrics) = metrics.handle.close() + +proc loadTime*(metrics: PerfMetrics): float32 = + var value: cfloat = 0 + checkGenAiStatus(ov_genai_perf_metrics_get_load_time( + metrics.native(), addr value), "get model load time") + result = float32(value) + +proc inputTokenCount*(metrics: PerfMetrics): int = + var value: csize_t = 0 + checkGenAiStatus(ov_genai_perf_metrics_get_num_input_tokens( + metrics.native(), addr value), "get input token count") + result = int(value) + +proc generatedTokenCount*(metrics: PerfMetrics): int = + var value: csize_t = 0 + checkGenAiStatus(ov_genai_perf_metrics_get_num_generation_tokens( + metrics.native(), addr value), "get generated token count") + result = int(value) + +proc timeToFirstToken*(metrics: PerfMetrics): tuple[mean, std: float32] = + var mean, deviation: cfloat = 0 + checkGenAiStatus(ov_genai_perf_metrics_get_ttft(metrics.native(), + addr mean, addr deviation), "get time to first token") + result = (float32(mean), float32(deviation)) + +proc timePerOutputToken*(metrics: PerfMetrics): tuple[mean, std: float32] = + var mean, deviation: cfloat = 0 + checkGenAiStatus(ov_genai_perf_metrics_get_tpot(metrics.native(), + addr mean, addr deviation), "get time per output token") + result = (float32(mean), float32(deviation)) + +proc throughput*(metrics: PerfMetrics): tuple[mean, std: float32] = + var mean, deviation: cfloat = 0 + checkGenAiStatus(ov_genai_perf_metrics_get_throughput(metrics.native(), + addr mean, addr deviation), "get generation throughput") + result = (float32(mean), float32(deviation)) + +type MetricPairGetter = proc (native: ptr ov_genai_perf_metrics; + mean, deviation: ptr cfloat): ov_status_e {.closure.} + +proc metricPair(metrics: PerfMetrics; getter: MetricPairGetter; + operation: string): tuple[mean, std: float32] = + var mean, deviation: cfloat = 0 + checkGenAiStatus(getter(metrics.native(), addr mean, addr deviation), + "get " & operation) + result = (float32(mean), float32(deviation)) + +proc inputTimePerToken*(metrics: PerfMetrics): tuple[mean, std: float32] = + metricPair(metrics, + proc (native: ptr ov_genai_perf_metrics; mean, deviation: ptr cfloat): + ov_status_e = + ov_genai_perf_metrics_get_ipot(native, mean, deviation), + "input time per token") + +proc inferenceDuration*(metrics: PerfMetrics): tuple[mean, std: float32] = + metricPair(metrics, + proc (native: ptr ov_genai_perf_metrics; mean, deviation: ptr cfloat): + ov_status_e = + ov_genai_perf_metrics_get_inference_duration(native, mean, deviation), + "inference duration") + +proc generationDuration*(metrics: PerfMetrics): tuple[mean, std: float32] = + metricPair(metrics, + proc (native: ptr ov_genai_perf_metrics; mean, deviation: ptr cfloat): + ov_status_e = + ov_genai_perf_metrics_get_generate_duration(native, mean, deviation), + "generation duration") + +proc tokenizationDuration*(metrics: PerfMetrics): tuple[mean, std: float32] = + metricPair(metrics, + proc (native: ptr ov_genai_perf_metrics; mean, deviation: ptr cfloat): + ov_status_e = + ov_genai_perf_metrics_get_tokenization_duration(native, mean, deviation), + "tokenization duration") + +proc detokenizationDuration*(metrics: PerfMetrics): tuple[mean, std: float32] = + metricPair(metrics, + proc (native: ptr ov_genai_perf_metrics; mean, deviation: ptr cfloat): + ov_status_e = + ov_genai_perf_metrics_get_detokenization_duration(native, mean, deviation), + "detokenization duration") + +proc chatTemplateDuration*(metrics: PerfMetrics): tuple[mean, std: float32] = + metricPair(metrics, + proc (native: ptr ov_genai_perf_metrics; mean, deviation: ptr cfloat): + ov_status_e = + ov_genai_perf_metrics_get_chat_template_duration(native, mean, deviation), + "chat template duration") + +proc addInPlace*(metrics: PerfMetrics; other: PerfMetrics) = + checkGenAiStatus(ov_genai_perf_metrics_add_in_place(metrics.native(), + other.native()), "add performance metrics") diff --git a/src/openvino/preprocess.nim b/src/openvino/preprocess.nim index 1ba3fff..1672faa 100644 --- a/src/openvino/preprocess.nim +++ b/src/openvino/preprocess.nim @@ -319,7 +319,8 @@ proc `$`*(output: OutputPostprocess): string = result.add("}") proc `$`*(plan: PreprocessPlan): string = - ## A summary of every input and output description, separated by `; `. + ## A summary of every input and output description, separated by a semicolon + ## and a space. var parts: seq[string] = @[] for input in plan.inputs: parts.add($input) diff --git a/src/openvino/private/genai_bridge.nim b/src/openvino/private/genai_bridge.nim new file mode 100644 index 0000000..066d90b --- /dev/null +++ b/src/openvino/private/genai_bridge.nim @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: Apache-2.0 + +## The single C ABI adapter needed for GenAI's three variadic constructors. +## All other GenAI functions are bound directly through the dynamic loader. + +import ../errors +import conversions + +{.emit: """ +#include +typedef int (*OpenVinoNimGenAiCreateFn)(const char*, const char*, size_t, + void**, ...); +int openvino_nim_genai_create_bridge(void* address, + char* model, + char* device, + size_t property_pairs, + char** properties, + void* output) { + OpenVinoNimGenAiCreateFn create = (OpenVinoNimGenAiCreateFn)address; + switch (property_pairs) { + case 0: return create(model, device, 0, (void**)output); + case 1: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1]); + case 2: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3]); + case 3: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5]); + case 4: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7]); + case 5: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9]); + case 6: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9], properties[10], properties[11]); + case 7: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9], properties[10], properties[11], properties[12], properties[13]); + case 8: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9], properties[10], properties[11], properties[12], properties[13], properties[14], properties[15]); + case 9: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9], properties[10], properties[11], properties[12], properties[13], properties[14], properties[15], properties[16], properties[17]); + case 10: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9], properties[10], properties[11], properties[12], properties[13], properties[14], properties[15], properties[16], properties[17], properties[18], properties[19]); + case 11: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9], properties[10], properties[11], properties[12], properties[13], properties[14], properties[15], properties[16], properties[17], properties[18], properties[19], properties[20], properties[21]); + case 12: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9], properties[10], properties[11], properties[12], properties[13], properties[14], properties[15], properties[16], properties[17], properties[18], properties[19], properties[20], properties[21], properties[22], properties[23]); + case 13: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9], properties[10], properties[11], properties[12], properties[13], properties[14], properties[15], properties[16], properties[17], properties[18], properties[19], properties[20], properties[21], properties[22], properties[23], properties[24], properties[25]); + case 14: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9], properties[10], properties[11], properties[12], properties[13], properties[14], properties[15], properties[16], properties[17], properties[18], properties[19], properties[20], properties[21], properties[22], properties[23], properties[24], properties[25], properties[26], properties[27]); + case 15: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9], properties[10], properties[11], properties[12], properties[13], properties[14], properties[15], properties[16], properties[17], properties[18], properties[19], properties[20], properties[21], properties[22], properties[23], properties[24], properties[25], properties[26], properties[27], properties[28], properties[29]); + case 16: return create(model, device, property_pairs * 2, (void**)output, properties[0], properties[1], properties[2], properties[3], properties[4], properties[5], properties[6], properties[7], properties[8], properties[9], properties[10], properties[11], properties[12], properties[13], properties[14], properties[15], properties[16], properties[17], properties[18], properties[19], properties[20], properties[21], properties[22], properties[23], properties[24], properties[25], properties[26], properties[27], properties[28], properties[29], properties[30], properties[31]); + default: return -14; + } +} +""".} + +proc cGenAiCreate(address: pointer; model, device: cstring; + propertyPairs: csize_t; properties: ptr cstring; + output: pointer): cint + {.importc: "openvino_nim_genai_create_bridge", cdecl.} + +proc createGenAiPipeline*[T](address: pointer; model, device: string; + properties: openArray[(string, string)]; + output: ptr ptr T): cint = + ## Calls one upstream variadic pipeline constructor without declaring a + ## C varargs procedure in Nim. Values are passed as the C API requires: + ## strings, including numeric property values. + if properties.len > 16: + raiseArgumentError("GenAI pipeline constructors accept at most 16 " & + "property pairs through this adapter") + checkCString(model, "GenAI model path") + checkCString(device, "GenAI device") + var rawProperties: seq[cstring] = @[] + for property in properties: + checkCString(property[0], "GenAI property key") + checkCString(property[1], "GenAI property value") + rawProperties.add(property[0].cstring) + rawProperties.add(property[1].cstring) + let rawPointer = if rawProperties.len == 0: nil + else: addr rawProperties[0] + # invariant: a pointer to an opaque GenAI handle slot has the same C ABI as + # the `void**` output parameter in all three upstream constructors. + result = cGenAiCreate(address, model.cstring, device.cstring, + csize_t(properties.len), rawPointer, + cast[pointer](output)) diff --git a/src/openvino/raw.nim b/src/openvino/raw.nim index 22e138a..2efacda 100644 --- a/src/openvino/raw.nim +++ b/src/openvino/raw.nim @@ -3,17 +3,19 @@ ## Explicit entry point for the OpenVINO C ABI layer. ## ## `import openvino/raw` gives access to declarations that mirror the pinned -## OpenVINO `2026.4.0` C headers. Nothing here is safe by construction: the -## types are raw pointers, ownership is the caller's problem, and failures -## arrive as `ov_status_e` values rather than exceptions. +## OpenVINO Runtime `2026.4.1` C headers and, under `raw/genai`, GenAI +## `2026.4.1.0` C headers. Nothing here is safe by construction: the +## types are raw pointers, ownership is the caller's problem, and native calls +## report upstream C status values rather than managed Nim exceptions. ## ## Prefer `import openvino`, which exposes the managed API. Reach for this ## layer only when the managed API cannot express what you need. The `0.x` ## series promises that these declarations match the pinned headers; it does ## **not** promise source stability for them. ## -## The one place this layer raises is symbol resolution, in -## `openvino/raw/loader`. The reason is recorded in +## Lazy symbol resolution may raise `OpenVinoLibraryError` from +## `openvino/raw/loader` or `GenAiLibraryError` from `openvino/raw/genai`. +## The reason for explicit loading is recorded in ## `docs/decisions/0001-symbol-loading.md`. ## ## Coverage, including what is deliberately not bound, is listed in @@ -24,6 +26,7 @@ import raw/compiled_model import raw/core import raw/dimension import raw/error +import raw/genai import raw/infer_request import raw/layout import raw/loader @@ -40,6 +43,7 @@ export compiled_model export core export dimension export error +export genai export infer_request export layout export loader diff --git a/src/openvino/raw/genai.nim b/src/openvino/raw/genai.nim new file mode 100644 index 0000000..25d5a6d --- /dev/null +++ b/src/openvino/raw/genai.nim @@ -0,0 +1,11 @@ +# SPDX-License-Identifier: Apache-2.0 + +## Optional, header-faithful OpenVINO GenAI C ABI. + +import genai/api +import genai/common +import genai/loader + +export api +export common +export loader diff --git a/src/openvino/raw/genai/api.nim b/src/openvino/raw/genai/api.nim new file mode 100644 index 0000000..36890d5 --- /dev/null +++ b/src/openvino/raw/genai/api.nim @@ -0,0 +1,1019 @@ +# SPDX-License-Identifier: Apache-2.0 + +## Header-faithful dynamic declarations for the OpenVINO GenAI C API. +## +## Generated against upstream OpenVINO GenAI 2026.4.1.0 C headers. The +## optional GenAI shared library is resolved lazily through `genaiImport`; +## importing this module does not require GenAI to be installed. + +import ../common +import ../tensor +import common +import loader + +{.push styleChecks: off.} + +proc ov_genai_chat_history_clear*(history: ptr ov_genai_chat_history): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_clear`. + +proc ov_genai_chat_history_create*(history: ptr ptr ov_genai_chat_history): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_create`. + +proc ov_genai_chat_history_create_from_json_container*( + history: ptr ptr ov_genai_chat_history, + messages: ptr ov_genai_json_container): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_create_from_json_container`. + +proc ov_genai_chat_history_empty*(history: ptr ov_genai_chat_history, + empty: ptr cint): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_empty`. + +proc ov_genai_chat_history_free*(history: ptr ov_genai_chat_history) {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_free`. + +proc ov_genai_chat_history_get_extra_context*( + history: ptr ov_genai_chat_history, + extra_context: ptr ptr ov_genai_json_container): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_get_extra_context`. + +proc ov_genai_chat_history_get_first*(history: ptr ov_genai_chat_history, + message: ptr ptr ov_genai_json_container): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_get_first`. + +proc ov_genai_chat_history_get_last*(history: ptr ov_genai_chat_history, + message: ptr ptr ov_genai_json_container): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_get_last`. + +proc ov_genai_chat_history_get_message*(history: ptr ov_genai_chat_history, + index: csize_t, + message: ptr ptr ov_genai_json_container): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_get_message`. + +proc ov_genai_chat_history_get_messages*(history: ptr ov_genai_chat_history, + messages: ptr ptr ov_genai_json_container): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_get_messages`. + +proc ov_genai_chat_history_get_tools*(history: ptr ov_genai_chat_history, + tools: ptr ptr ov_genai_json_container): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_get_tools`. + +proc ov_genai_chat_history_pop_back*(history: ptr ov_genai_chat_history): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_pop_back`. + +proc ov_genai_chat_history_push_back*(history: ptr ov_genai_chat_history, + message: ptr ov_genai_json_container): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_push_back`. + +proc ov_genai_chat_history_set_extra_context*( + history: ptr ov_genai_chat_history, + extra_context: ptr ov_genai_json_container): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_set_extra_context`. + +proc ov_genai_chat_history_set_tools*(history: ptr ov_genai_chat_history, + tools: ptr ov_genai_json_container): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_set_tools`. + +proc ov_genai_chat_history_size*(history: ptr ov_genai_chat_history, + size: ptr csize_t): ov_genai_chat_history_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_chat_history_size`. + +proc ov_genai_decoded_results_create*(results: ptr ptr ov_genai_decoded_results): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_decoded_results_create`. + +proc ov_genai_decoded_results_free*(results: ptr ov_genai_decoded_results) {.genaiImport.} + + ## Upstream C function `ov_genai_decoded_results_free`. + +proc ov_genai_decoded_results_get_perf_metrics*( + results: ptr ov_genai_decoded_results, + metrics: ptr ptr ov_genai_perf_metrics): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_decoded_results_get_perf_metrics`. + +proc ov_genai_decoded_results_get_string*(results: ptr ov_genai_decoded_results, + output: cstring, output_size: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_decoded_results_get_string`. + +proc ov_genai_decoded_results_perf_metrics_free*( + metrics: ptr ov_genai_perf_metrics) {.genaiImport.} + + ## Upstream C function `ov_genai_decoded_results_perf_metrics_free`. + +proc ov_genai_generation_config_create*( + config: ptr ptr ov_genai_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_create`. + +proc ov_genai_generation_config_create_from_json*(json_path: cstring, + config: ptr ptr ov_genai_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_create_from_json`. + +proc ov_genai_generation_config_free*(handle: ptr ov_genai_generation_config) {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_free`. + +proc ov_genai_generation_config_get_max_new_tokens*( + config: ptr ov_genai_generation_config, + max_new_tokens: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_get_max_new_tokens`. + +proc ov_genai_generation_config_set_assistant_confidence_threshold*( + config: ptr ov_genai_generation_config, + value: cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_assistant_confidence_threshold`. + +proc ov_genai_generation_config_set_diversity_penalty*( + config: ptr ov_genai_generation_config, + value: cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_diversity_penalty`. + +proc ov_genai_generation_config_set_do_sample*( + config: ptr ov_genai_generation_config, + value: bool): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_do_sample`. + +proc ov_genai_generation_config_set_echo*( + config: ptr ov_genai_generation_config, + value: bool): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_echo`. + +proc ov_genai_generation_config_set_eos_token_id*( + config: ptr ov_genai_generation_config, + id: int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_eos_token_id`. + +proc ov_genai_generation_config_set_frequency_penalty*( + config: ptr ov_genai_generation_config, + value: cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_frequency_penalty`. + +proc ov_genai_generation_config_set_ignore_eos*( + config: ptr ov_genai_generation_config, + value: bool): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_ignore_eos`. + +proc ov_genai_generation_config_set_include_stop_str_in_output*( + config: ptr ov_genai_generation_config, + value: bool): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_include_stop_str_in_output`. + +proc ov_genai_generation_config_set_length_penalty*( + config: ptr ov_genai_generation_config, + value: cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_length_penalty`. + +proc ov_genai_generation_config_set_logprobs*( + config: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_logprobs`. + +proc ov_genai_generation_config_set_max_length*( + config: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_max_length`. + +proc ov_genai_generation_config_set_max_new_tokens*( + handle: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_max_new_tokens`. + +proc ov_genai_generation_config_set_max_ngram_size*( + config: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_max_ngram_size`. + +proc ov_genai_generation_config_set_min_new_tokens*( + config: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_min_new_tokens`. + +proc ov_genai_generation_config_set_min_p*( + config: ptr ov_genai_generation_config, + value: cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_min_p`. + +proc ov_genai_generation_config_set_no_repeat_ngram_size*( + config: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_no_repeat_ngram_size`. + +proc ov_genai_generation_config_set_num_assistant_tokens*( + config: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_num_assistant_tokens`. + +proc ov_genai_generation_config_set_num_beam_groups*( + config: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_num_beam_groups`. + +proc ov_genai_generation_config_set_num_beams*( + config: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_num_beams`. + +proc ov_genai_generation_config_set_num_return_sequences*( + config: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_num_return_sequences`. + +proc ov_genai_generation_config_set_presence_penalty*( + config: ptr ov_genai_generation_config, + value: cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_presence_penalty`. + +proc ov_genai_generation_config_set_repetition_penalty*( + config: ptr ov_genai_generation_config, + value: cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_repetition_penalty`. + +proc ov_genai_generation_config_set_rng_seed*( + config: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_rng_seed`. + +proc ov_genai_generation_config_set_stop_criteria*( + config: ptr ov_genai_generation_config, + value: StopCriteria): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_stop_criteria`. + +proc ov_genai_generation_config_set_stop_strings*( + config: ptr ov_genai_generation_config, strings: ptr cstring, + count: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_stop_strings`. + +proc ov_genai_generation_config_set_stop_token_ids*( + config: ptr ov_genai_generation_config, token_ids: ptr int64, + token_ids_num: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_stop_token_ids`. + +proc ov_genai_generation_config_set_temperature*( + config: ptr ov_genai_generation_config, + value: cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_temperature`. + +proc ov_genai_generation_config_set_top_k*( + config: ptr ov_genai_generation_config, + value: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_top_k`. + +proc ov_genai_generation_config_set_top_p*( + config: ptr ov_genai_generation_config, + value: cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_set_top_p`. + +proc ov_genai_generation_config_validate*( + config: ptr ov_genai_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_generation_config_validate`. + +proc ov_genai_json_container_copy*(source: ptr ov_genai_json_container, + target: ptr ptr ov_genai_json_container): ov_genai_json_container_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_json_container_copy`. + +proc ov_genai_json_container_create*(container: ptr ptr ov_genai_json_container): ov_genai_json_container_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_json_container_create`. + +proc ov_genai_json_container_create_array*( + container: ptr ptr ov_genai_json_container): ov_genai_json_container_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_json_container_create_array`. + +proc ov_genai_json_container_create_from_json_string*( + container: ptr ptr ov_genai_json_container, + json_str: cstring): ov_genai_json_container_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_json_container_create_from_json_string`. + +proc ov_genai_json_container_create_object*( + container: ptr ptr ov_genai_json_container): ov_genai_json_container_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_json_container_create_object`. + +proc ov_genai_json_container_free*(container: ptr ov_genai_json_container) {.genaiImport.} + + ## Upstream C function `ov_genai_json_container_free`. + +proc ov_genai_json_container_to_json_string*( + container: ptr ov_genai_json_container, output: cstring, + output_size: ptr csize_t): ov_genai_json_container_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_json_container_to_json_string`. + +proc ov_genai_llm_pipeline_finish_chat*( + pipe: ptr ov_genai_llm_pipeline): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_llm_pipeline_finish_chat`. + +proc ov_genai_llm_pipeline_free*(pipe: ptr ov_genai_llm_pipeline) {.genaiImport.} + + ## Upstream C function `ov_genai_llm_pipeline_free`. + +proc ov_genai_llm_pipeline_generate*(pipe: ptr ov_genai_llm_pipeline, + inputs: cstring, config: ptr ov_genai_generation_config, + streamer: ptr ov_genai_streamer_callback, + results: ptr ptr ov_genai_decoded_results): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_llm_pipeline_generate`. + +proc ov_genai_llm_pipeline_generate_with_history*( + pipe: ptr ov_genai_llm_pipeline, history: ptr ov_genai_chat_history, + config: ptr ov_genai_generation_config, + streamer: ptr ov_genai_streamer_callback, + results: ptr ptr ov_genai_decoded_results): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_llm_pipeline_generate_with_history`. + +proc ov_genai_llm_pipeline_get_generation_config*( + pipe: ptr ov_genai_llm_pipeline, + config: ptr ptr ov_genai_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_llm_pipeline_get_generation_config`. + +proc ov_genai_llm_pipeline_set_generation_config*( + pipe: ptr ov_genai_llm_pipeline, + config: ptr ov_genai_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_llm_pipeline_set_generation_config`. + +proc ov_genai_llm_pipeline_start_chat*(pipe: ptr ov_genai_llm_pipeline): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_llm_pipeline_start_chat`. + +proc ov_genai_perf_metrics_add_in_place*(left: ptr ov_genai_perf_metrics, + right: ptr ov_genai_perf_metrics): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_add_in_place`. + +proc ov_genai_perf_metrics_get_chat_template_duration*( + metrics: ptr ov_genai_perf_metrics, mean: ptr cfloat, + std: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_chat_template_duration`. + +proc ov_genai_perf_metrics_get_detokenization_duration*( + metrics: ptr ov_genai_perf_metrics, mean: ptr cfloat, + std: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_detokenization_duration`. + +proc ov_genai_perf_metrics_get_generate_duration*( + metrics: ptr ov_genai_perf_metrics, mean: ptr cfloat, + std: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_generate_duration`. + +proc ov_genai_perf_metrics_get_inference_duration*( + metrics: ptr ov_genai_perf_metrics, mean: ptr cfloat, + std: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_inference_duration`. + +proc ov_genai_perf_metrics_get_ipot*(metrics: ptr ov_genai_perf_metrics, + mean: ptr cfloat, std: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_ipot`. + +proc ov_genai_perf_metrics_get_load_time*(metrics: ptr ov_genai_perf_metrics, + load_time: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_load_time`. + +proc ov_genai_perf_metrics_get_num_generation_tokens*( + metrics: ptr ov_genai_perf_metrics, + num_generation_tokens: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_num_generation_tokens`. + +proc ov_genai_perf_metrics_get_num_input_tokens*( + metrics: ptr ov_genai_perf_metrics, + num_input_tokens: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_num_input_tokens`. + +proc ov_genai_perf_metrics_get_throughput*(metrics: ptr ov_genai_perf_metrics, + mean: ptr cfloat, std: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_throughput`. + +proc ov_genai_perf_metrics_get_tokenization_duration*( + metrics: ptr ov_genai_perf_metrics, mean: ptr cfloat, + std: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_tokenization_duration`. + +proc ov_genai_perf_metrics_get_tpot*(metrics: ptr ov_genai_perf_metrics, + mean: ptr cfloat, std: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_tpot`. + +proc ov_genai_perf_metrics_get_ttft*(metrics: ptr ov_genai_perf_metrics, + mean: ptr cfloat, std: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_perf_metrics_get_ttft`. + +proc ov_genai_vlm_decoded_results_create*( + results: ptr ptr ov_genai_vlm_decoded_results): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_decoded_results_create`. + +proc ov_genai_vlm_decoded_results_free*( + results: ptr ov_genai_vlm_decoded_results) {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_decoded_results_free`. + +proc ov_genai_vlm_decoded_results_get_perf_metrics*( + results: ptr ov_genai_vlm_decoded_results, + metrics: ptr ptr ov_genai_perf_metrics): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_decoded_results_get_perf_metrics`. + +proc ov_genai_vlm_decoded_results_get_string*( + results: ptr ov_genai_vlm_decoded_results, output: cstring, + output_size: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_decoded_results_get_string`. + +proc ov_genai_vlm_decoded_results_perf_metrics_free*( + metrics: ptr ov_genai_perf_metrics) {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_decoded_results_perf_metrics_free`. + +proc ov_genai_vlm_pipeline_finish_chat*( + pipe: ptr ov_genai_vlm_pipeline): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_pipeline_finish_chat`. + +proc ov_genai_vlm_pipeline_free*(pipe: ptr ov_genai_vlm_pipeline) {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_pipeline_free`. + +proc ov_genai_vlm_pipeline_generate*(pipe: ptr ov_genai_vlm_pipeline, + text_inputs: cstring, rgbs: ptr ptr ov_tensor_t, num_images: csize_t, + config: ptr ov_genai_generation_config, + streamer: ptr ov_genai_streamer_callback, + results: ptr ptr ov_genai_vlm_decoded_results): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_pipeline_generate`. + +proc ov_genai_vlm_pipeline_generate_with_history*( + pipe: ptr ov_genai_vlm_pipeline, history: ptr ov_genai_chat_history, + rgbs: ptr ptr ov_tensor_t, num_images: csize_t, + config: ptr ov_genai_generation_config, + streamer: ptr ov_genai_streamer_callback, + results: ptr ptr ov_genai_vlm_decoded_results): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_pipeline_generate_with_history`. + +proc ov_genai_vlm_pipeline_get_generation_config*( + pipe: ptr ov_genai_vlm_pipeline, + config: ptr ptr ov_genai_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_pipeline_get_generation_config`. + +proc ov_genai_vlm_pipeline_set_generation_config*( + pipe: ptr ov_genai_vlm_pipeline, + config: ptr ov_genai_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_pipeline_set_generation_config`. + +proc ov_genai_vlm_pipeline_start_chat*(pipe: ptr ov_genai_vlm_pipeline): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_vlm_pipeline_start_chat`. + +proc ov_genai_whisper_decoded_result_chunk_create*( + chunk: ptr ptr ov_genai_whisper_decoded_result_chunk): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_result_chunk_create`. + +proc ov_genai_whisper_decoded_result_chunk_free*( + chunk: ptr ov_genai_whisper_decoded_result_chunk) {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_result_chunk_free`. + +proc ov_genai_whisper_decoded_result_chunk_get_end_ts*( + chunk: ptr ov_genai_whisper_decoded_result_chunk, + end_ts: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_result_chunk_get_end_ts`. + +proc ov_genai_whisper_decoded_result_chunk_get_start_ts*( + chunk: ptr ov_genai_whisper_decoded_result_chunk, + start_ts: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_result_chunk_get_start_ts`. + +proc ov_genai_whisper_decoded_result_chunk_get_text*( + chunk: ptr ov_genai_whisper_decoded_result_chunk, text: cstring, + text_size: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_result_chunk_get_text`. + +proc ov_genai_whisper_decoded_results_create*( + results: ptr ptr ov_genai_whisper_decoded_results): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_results_create`. + +proc ov_genai_whisper_decoded_results_free*( + results: ptr ov_genai_whisper_decoded_results) {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_results_free`. + +proc ov_genai_whisper_decoded_results_get_chunk_at*( + results: ptr ov_genai_whisper_decoded_results, index: csize_t, + chunk: ptr ptr ov_genai_whisper_decoded_result_chunk): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_results_get_chunk_at`. + +proc ov_genai_whisper_decoded_results_get_chunks_count*( + results: ptr ov_genai_whisper_decoded_results, + count: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_results_get_chunks_count`. + +proc ov_genai_whisper_decoded_results_get_perf_metrics*( + results: ptr ov_genai_whisper_decoded_results, + metrics: ptr ptr ov_genai_perf_metrics): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_results_get_perf_metrics`. + +proc ov_genai_whisper_decoded_results_get_score_at*( + results: ptr ov_genai_whisper_decoded_results, index: csize_t, + score: ptr cfloat): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_results_get_score_at`. + +proc ov_genai_whisper_decoded_results_get_string*( + results: ptr ov_genai_whisper_decoded_results, output: cstring, + output_size: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_results_get_string`. + +proc ov_genai_whisper_decoded_results_get_text_at*( + results: ptr ov_genai_whisper_decoded_results, index: csize_t, text: cstring, + text_size: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_results_get_text_at`. + +proc ov_genai_whisper_decoded_results_get_texts_count*( + results: ptr ov_genai_whisper_decoded_results, + count: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_results_get_texts_count`. + +proc ov_genai_whisper_decoded_results_has_chunks*( + results: ptr ov_genai_whisper_decoded_results, + has_chunks: ptr bool): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_decoded_results_has_chunks`. + +proc ov_genai_whisper_generation_config_create*( + config: ptr ptr ov_genai_whisper_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_create`. + +proc ov_genai_whisper_generation_config_create_from_json*(json_path: cstring, + config: ptr ptr ov_genai_whisper_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_create_from_json`. + +proc ov_genai_whisper_generation_config_free*( + config: ptr ov_genai_whisper_generation_config) {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_free`. + +proc ov_genai_whisper_generation_config_get_begin_suppress_tokens*( + config: ptr ov_genai_whisper_generation_config, tokens: ptr int64, + tokens_count: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_begin_suppress_tokens`. + +proc ov_genai_whisper_generation_config_get_begin_suppress_tokens_count*( + config: ptr ov_genai_whisper_generation_config, + tokens_count: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_begin_suppress_tokens_count`. + +proc ov_genai_whisper_generation_config_get_decoder_start_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: ptr int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_decoder_start_token_id`. + +proc ov_genai_whisper_generation_config_get_generation_config*( + config: ptr ov_genai_whisper_generation_config, + generation_config: ptr ptr ov_genai_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_generation_config`. + +proc ov_genai_whisper_generation_config_get_hotwords*( + config: ptr ov_genai_whisper_generation_config, hotwords: cstring, + hotwords_size: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_hotwords`. + +proc ov_genai_whisper_generation_config_get_initial_prompt*( + config: ptr ov_genai_whisper_generation_config, initial_prompt: cstring, + prompt_size: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_initial_prompt`. + +proc ov_genai_whisper_generation_config_get_is_multilingual*( + config: ptr ov_genai_whisper_generation_config, + is_multilingual: ptr bool): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_is_multilingual`. + +proc ov_genai_whisper_generation_config_get_language*( + config: ptr ov_genai_whisper_generation_config, language: cstring, + language_size: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_language`. + +proc ov_genai_whisper_generation_config_get_max_initial_timestamp_index*( + config: ptr ov_genai_whisper_generation_config, + index: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_max_initial_timestamp_index`. + +proc ov_genai_whisper_generation_config_get_no_timestamps_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: ptr int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_no_timestamps_token_id`. + +proc ov_genai_whisper_generation_config_get_pad_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: ptr int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_pad_token_id`. + +proc ov_genai_whisper_generation_config_get_prev_sot_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: ptr int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_prev_sot_token_id`. + +proc ov_genai_whisper_generation_config_get_return_timestamps*( + config: ptr ov_genai_whisper_generation_config, + return_timestamps: ptr bool): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_return_timestamps`. + +proc ov_genai_whisper_generation_config_get_suppress_tokens*( + config: ptr ov_genai_whisper_generation_config, tokens: ptr int64, + tokens_count: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_suppress_tokens`. + +proc ov_genai_whisper_generation_config_get_suppress_tokens_count*( + config: ptr ov_genai_whisper_generation_config, + tokens_count: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_suppress_tokens_count`. + +proc ov_genai_whisper_generation_config_get_task*( + config: ptr ov_genai_whisper_generation_config, task: cstring, + task_size: ptr csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_task`. + +proc ov_genai_whisper_generation_config_get_transcribe_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: ptr int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_transcribe_token_id`. + +proc ov_genai_whisper_generation_config_get_translate_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: ptr int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_get_translate_token_id`. + +proc ov_genai_whisper_generation_config_set_begin_suppress_tokens*( + config: ptr ov_genai_whisper_generation_config, tokens: ptr int64, + tokens_count: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_begin_suppress_tokens`. + +proc ov_genai_whisper_generation_config_set_decoder_start_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_decoder_start_token_id`. + +proc ov_genai_whisper_generation_config_set_hotwords*( + config: ptr ov_genai_whisper_generation_config, + hotwords: cstring): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_hotwords`. + +proc ov_genai_whisper_generation_config_set_initial_prompt*( + config: ptr ov_genai_whisper_generation_config, + initial_prompt: cstring): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_initial_prompt`. + +proc ov_genai_whisper_generation_config_set_is_multilingual*( + config: ptr ov_genai_whisper_generation_config, + is_multilingual: bool): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_is_multilingual`. + +proc ov_genai_whisper_generation_config_set_language*( + config: ptr ov_genai_whisper_generation_config, + language: cstring): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_language`. + +proc ov_genai_whisper_generation_config_set_max_initial_timestamp_index*( + config: ptr ov_genai_whisper_generation_config, + index: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_max_initial_timestamp_index`. + +proc ov_genai_whisper_generation_config_set_no_timestamps_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_no_timestamps_token_id`. + +proc ov_genai_whisper_generation_config_set_pad_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_pad_token_id`. + +proc ov_genai_whisper_generation_config_set_prev_sot_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_prev_sot_token_id`. + +proc ov_genai_whisper_generation_config_set_return_timestamps*( + config: ptr ov_genai_whisper_generation_config, + return_timestamps: bool): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_return_timestamps`. + +proc ov_genai_whisper_generation_config_set_suppress_tokens*( + config: ptr ov_genai_whisper_generation_config, tokens: ptr int64, + tokens_count: csize_t): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_suppress_tokens`. + +proc ov_genai_whisper_generation_config_set_task*( + config: ptr ov_genai_whisper_generation_config, + task: cstring): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_task`. + +proc ov_genai_whisper_generation_config_set_transcribe_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_transcribe_token_id`. + +proc ov_genai_whisper_generation_config_set_translate_token_id*( + config: ptr ov_genai_whisper_generation_config, + token_id: int64): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_set_translate_token_id`. + +proc ov_genai_whisper_generation_config_validate*( + config: ptr ov_genai_whisper_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_generation_config_validate`. + +proc ov_genai_whisper_pipeline_free*(pipeline: ptr ov_genai_whisper_pipeline) {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_pipeline_free`. + +proc ov_genai_whisper_pipeline_generate*( + pipeline: ptr ov_genai_whisper_pipeline, raw_speech: ptr cfloat, + raw_speech_size: csize_t, config: ptr ov_genai_whisper_generation_config, + results: ptr ptr ov_genai_whisper_decoded_results): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_pipeline_generate`. + +proc ov_genai_whisper_pipeline_get_generation_config*( + pipeline: ptr ov_genai_whisper_pipeline, + config: ptr ptr ov_genai_whisper_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_pipeline_get_generation_config`. + +proc ov_genai_whisper_pipeline_set_generation_config*( + pipeline: ptr ov_genai_whisper_pipeline, + config: ptr ov_genai_whisper_generation_config): ov_status_e {.genaiImport.} + + ## Upstream C function `ov_genai_whisper_pipeline_set_generation_config`. + +const + GenAiApiSymbols* = array[153, string]([ + "ov_genai_chat_history_clear", + "ov_genai_chat_history_create", + "ov_genai_chat_history_create_from_json_container", + "ov_genai_chat_history_empty", + "ov_genai_chat_history_free", + "ov_genai_chat_history_get_extra_context", + "ov_genai_chat_history_get_first", + "ov_genai_chat_history_get_last", + "ov_genai_chat_history_get_message", + "ov_genai_chat_history_get_messages", + "ov_genai_chat_history_get_tools", + "ov_genai_chat_history_pop_back", + "ov_genai_chat_history_push_back", + "ov_genai_chat_history_set_extra_context", + "ov_genai_chat_history_set_tools", + "ov_genai_chat_history_size", + "ov_genai_decoded_results_create", + "ov_genai_decoded_results_free", + "ov_genai_decoded_results_get_perf_metrics", + "ov_genai_decoded_results_get_string", + "ov_genai_decoded_results_perf_metrics_free", + "ov_genai_generation_config_create", + "ov_genai_generation_config_create_from_json", + "ov_genai_generation_config_free", + "ov_genai_generation_config_get_max_new_tokens", + "ov_genai_generation_config_set_assistant_confidence_threshold", + "ov_genai_generation_config_set_diversity_penalty", + "ov_genai_generation_config_set_do_sample", + "ov_genai_generation_config_set_echo", + "ov_genai_generation_config_set_eos_token_id", + "ov_genai_generation_config_set_frequency_penalty", + "ov_genai_generation_config_set_ignore_eos", + "ov_genai_generation_config_set_include_stop_str_in_output", + "ov_genai_generation_config_set_length_penalty", + "ov_genai_generation_config_set_logprobs", + "ov_genai_generation_config_set_max_length", + "ov_genai_generation_config_set_max_new_tokens", + "ov_genai_generation_config_set_max_ngram_size", + "ov_genai_generation_config_set_min_new_tokens", + "ov_genai_generation_config_set_min_p", + "ov_genai_generation_config_set_no_repeat_ngram_size", + "ov_genai_generation_config_set_num_assistant_tokens", + "ov_genai_generation_config_set_num_beam_groups", + "ov_genai_generation_config_set_num_beams", + "ov_genai_generation_config_set_num_return_sequences", + "ov_genai_generation_config_set_presence_penalty", + "ov_genai_generation_config_set_repetition_penalty", + "ov_genai_generation_config_set_rng_seed", + "ov_genai_generation_config_set_stop_criteria", + "ov_genai_generation_config_set_stop_strings", + "ov_genai_generation_config_set_stop_token_ids", + "ov_genai_generation_config_set_temperature", + "ov_genai_generation_config_set_top_k", + "ov_genai_generation_config_set_top_p", + "ov_genai_generation_config_validate", + "ov_genai_json_container_copy", + "ov_genai_json_container_create", + "ov_genai_json_container_create_array", + "ov_genai_json_container_create_from_json_string", + "ov_genai_json_container_create_object", + "ov_genai_json_container_free", + "ov_genai_json_container_to_json_string", + "ov_genai_llm_pipeline_create", + "ov_genai_llm_pipeline_finish_chat", + "ov_genai_llm_pipeline_free", + "ov_genai_llm_pipeline_generate", + "ov_genai_llm_pipeline_generate_with_history", + "ov_genai_llm_pipeline_get_generation_config", + "ov_genai_llm_pipeline_set_generation_config", + "ov_genai_llm_pipeline_start_chat", + "ov_genai_perf_metrics_add_in_place", + "ov_genai_perf_metrics_get_chat_template_duration", + "ov_genai_perf_metrics_get_detokenization_duration", + "ov_genai_perf_metrics_get_generate_duration", + "ov_genai_perf_metrics_get_inference_duration", + "ov_genai_perf_metrics_get_ipot", + "ov_genai_perf_metrics_get_load_time", + "ov_genai_perf_metrics_get_num_generation_tokens", + "ov_genai_perf_metrics_get_num_input_tokens", + "ov_genai_perf_metrics_get_throughput", + "ov_genai_perf_metrics_get_tokenization_duration", + "ov_genai_perf_metrics_get_tpot", + "ov_genai_perf_metrics_get_ttft", + "ov_genai_vlm_decoded_results_create", + "ov_genai_vlm_decoded_results_free", + "ov_genai_vlm_decoded_results_get_perf_metrics", + "ov_genai_vlm_decoded_results_get_string", + "ov_genai_vlm_decoded_results_perf_metrics_free", + "ov_genai_vlm_pipeline_create", + "ov_genai_vlm_pipeline_finish_chat", + "ov_genai_vlm_pipeline_free", + "ov_genai_vlm_pipeline_generate", + "ov_genai_vlm_pipeline_generate_with_history", + "ov_genai_vlm_pipeline_get_generation_config", + "ov_genai_vlm_pipeline_set_generation_config", + "ov_genai_vlm_pipeline_start_chat", + "ov_genai_whisper_decoded_result_chunk_create", + "ov_genai_whisper_decoded_result_chunk_free", + "ov_genai_whisper_decoded_result_chunk_get_end_ts", + "ov_genai_whisper_decoded_result_chunk_get_start_ts", + "ov_genai_whisper_decoded_result_chunk_get_text", + "ov_genai_whisper_decoded_results_create", + "ov_genai_whisper_decoded_results_free", + "ov_genai_whisper_decoded_results_get_chunk_at", + "ov_genai_whisper_decoded_results_get_chunks_count", + "ov_genai_whisper_decoded_results_get_perf_metrics", + "ov_genai_whisper_decoded_results_get_score_at", + "ov_genai_whisper_decoded_results_get_string", + "ov_genai_whisper_decoded_results_get_text_at", + "ov_genai_whisper_decoded_results_get_texts_count", + "ov_genai_whisper_decoded_results_has_chunks", + "ov_genai_whisper_generation_config_create", + "ov_genai_whisper_generation_config_create_from_json", + "ov_genai_whisper_generation_config_free", + "ov_genai_whisper_generation_config_get_begin_suppress_tokens", + "ov_genai_whisper_generation_config_get_begin_suppress_tokens_count", + "ov_genai_whisper_generation_config_get_decoder_start_token_id", + "ov_genai_whisper_generation_config_get_generation_config", + "ov_genai_whisper_generation_config_get_hotwords", + "ov_genai_whisper_generation_config_get_initial_prompt", + "ov_genai_whisper_generation_config_get_is_multilingual", + "ov_genai_whisper_generation_config_get_language", + "ov_genai_whisper_generation_config_get_max_initial_timestamp_index", + "ov_genai_whisper_generation_config_get_no_timestamps_token_id", + "ov_genai_whisper_generation_config_get_pad_token_id", + "ov_genai_whisper_generation_config_get_prev_sot_token_id", + "ov_genai_whisper_generation_config_get_return_timestamps", + "ov_genai_whisper_generation_config_get_suppress_tokens", + "ov_genai_whisper_generation_config_get_suppress_tokens_count", + "ov_genai_whisper_generation_config_get_task", + "ov_genai_whisper_generation_config_get_transcribe_token_id", + "ov_genai_whisper_generation_config_get_translate_token_id", + "ov_genai_whisper_generation_config_set_begin_suppress_tokens", + "ov_genai_whisper_generation_config_set_decoder_start_token_id", + "ov_genai_whisper_generation_config_set_hotwords", + "ov_genai_whisper_generation_config_set_initial_prompt", + "ov_genai_whisper_generation_config_set_is_multilingual", + "ov_genai_whisper_generation_config_set_language", + "ov_genai_whisper_generation_config_set_max_initial_timestamp_index", + "ov_genai_whisper_generation_config_set_no_timestamps_token_id", + "ov_genai_whisper_generation_config_set_pad_token_id", + "ov_genai_whisper_generation_config_set_prev_sot_token_id", + "ov_genai_whisper_generation_config_set_return_timestamps", + "ov_genai_whisper_generation_config_set_suppress_tokens", + "ov_genai_whisper_generation_config_set_task", + "ov_genai_whisper_generation_config_set_transcribe_token_id", + "ov_genai_whisper_generation_config_set_translate_token_id", + "ov_genai_whisper_generation_config_validate", + "ov_genai_whisper_pipeline_create", + "ov_genai_whisper_pipeline_free", + "ov_genai_whisper_pipeline_generate", + "ov_genai_whisper_pipeline_get_generation_config", + "ov_genai_whisper_pipeline_set_generation_config" + ]) + +{.pop.} diff --git a/src/openvino/raw/genai/common.nim b/src/openvino/raw/genai/common.nim new file mode 100644 index 0000000..996aea7 --- /dev/null +++ b/src/openvino/raw/genai/common.nim @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: Apache-2.0 + +## Shared opaque types and enums from OpenVINO GenAI C 2026.4.1.0. + +import ../common +import ../tensor + +export ov_status_e, ov_tensor_t + +type + ov_genai_chat_history* = object + ov_genai_decoded_results* = object + ov_genai_generation_config* = object + ov_genai_json_container* = object + ov_genai_llm_pipeline* = object + ov_genai_perf_metrics* = object + ov_genai_vlm_decoded_results* = object + ov_genai_vlm_pipeline* = object + ov_genai_whisper_decoded_result_chunk * = object + ov_genai_whisper_decoded_results* = object + ov_genai_whisper_generation_config* = object + ov_genai_whisper_pipeline* = object + + StopCriteria* = cint + ## Upstream grouped beam-search termination policy. + ov_genai_chat_history_status_e* = cint + ov_genai_json_container_status_e* = cint + ov_genai_streaming_status_e* = cint + + ov_genai_streamer_callback_fn* = proc (text: cstring; args: pointer): + ov_genai_streaming_status_e {.cdecl.} + ## C callback called synchronously from pipeline generation. + + ov_genai_streamer_callback* = object + callbackFunc*: ov_genai_streamer_callback_fn + args*: pointer + +const + EARLY* = StopCriteria(0) + HEURISTIC* = StopCriteria(1) + NEVER* = StopCriteria(2) + + OV_GENAI_STREAMING_STATUS_RUNNING* = ov_genai_streaming_status_e(0) + OV_GENAI_STREAMING_STATUS_STOP* = ov_genai_streaming_status_e(1) + OV_GENAI_STREAMING_STATUS_CANCEL* = ov_genai_streaming_status_e(2) + + OV_GENAI_CHAT_HISTORY_OK* = ov_genai_chat_history_status_e(0) + OV_GENAI_CHAT_HISTORY_INVALID_PARAM* = ov_genai_chat_history_status_e(-1) + OV_GENAI_CHAT_HISTORY_OUT_OF_BOUNDS* = ov_genai_chat_history_status_e(-2) + OV_GENAI_CHAT_HISTORY_EMPTY* = ov_genai_chat_history_status_e(-3) + OV_GENAI_CHAT_HISTORY_INVALID_JSON* = ov_genai_chat_history_status_e(-4) + OV_GENAI_CHAT_HISTORY_ERROR* = ov_genai_chat_history_status_e(-5) + + OV_GENAI_JSON_CONTAINER_OK* = ov_genai_json_container_status_e(0) + OV_GENAI_JSON_CONTAINER_INVALID_PARAM * = ov_genai_json_container_status_e(-1) + OV_GENAI_JSON_CONTAINER_INVALID_JSON * = ov_genai_json_container_status_e(-2) + OV_GENAI_JSON_CONTAINER_OUT_OF_BOUNDS * = ov_genai_json_container_status_e(-3) + OV_GENAI_JSON_CONTAINER_ERROR* = ov_genai_json_container_status_e(-4) diff --git a/src/openvino/raw/genai/loader.nim b/src/openvino/raw/genai/loader.nim new file mode 100644 index 0000000..26c67ff --- /dev/null +++ b/src/openvino/raw/genai/loader.nim @@ -0,0 +1,118 @@ +# SPDX-License-Identifier: Apache-2.0 + +## Lazy loading of the optional OpenVINO GenAI C shared library. + +import std/[dynlib, macros, os] + +import ../../version + +const openvinoGenAiLib* {.strdefine.} = "" + ## Compile-time override, for example `-d:openvinoGenAiLib=/path/to/lib`. + +const genAiSoSeriesPrefix = + $(TargetOpenVinoMajor mod 100) & $TargetOpenVinoMinor +const genAiSoVersionSuffix = genAiSoSeriesPrefix & $TargetOpenVinoPatch + +type GenAiLibraryError* = object of CatchableError + symbol*: string + attempted*: seq[string] + +when defined(windows): + const platformLibraries = ["openvino_genai_c.dll"] +elif defined(macosx): + const platformLibraries = ["libopenvino_genai_c.dylib"] +else: + const platformLibraries = [ + "libopenvino_genai_c.so", + "libopenvino_genai_c.so." & genAiSoVersionSuffix] + +var genAiHandle: LibHandle = nil + +proc candidateGenAiLibraries*(): seq[string] = + if openvinoGenAiLib.len > 0: + return @[openvinoGenAiLib] + let configured = getEnv("OPENVINO_GENAI_C_LIBRARY") + if configured.len > 0: + return @[configured] + result = @[] + for name in platformLibraries: + result.add(name) + when not defined(windows) and not defined(macosx): + for patch in countdown(TargetOpenVinoPatch - 1, 0): + result.add("libopenvino_genai_c.so." & genAiSoSeriesPrefix & $patch) + +proc genAiLibrary(): LibHandle = + if genAiHandle != nil: + return genAiHandle + let candidates = candidateGenAiLibraries() + for candidate in candidates: + let handle = loadLib(candidate) + if handle != nil: + genAiHandle = handle + return handle + var message = "Could not load the optional OpenVINO GenAI C API library.\n" + message.add(" Expected GenAI baseline: 2026.4.1.0\n") + message.add(" Library names tried:\n") + for candidate in candidates: + message.add(" " & candidate & "\n") + message.add(" Install/build the matching `openvino_genai_c` library and " & + "its OpenVINO GenAI, OpenVINO Runtime and tokenizer dependencies, or " & + "set `-d:openvinoGenAiLib=`. See docs/genai.md.") + var err = newException(GenAiLibraryError, message) + err.attempted = candidates + raise err + +proc genAiFunctionSymbol*(name: string): pointer = + let address = genAiLibrary().symAddr(name.cstring) + if address == nil: + var err = newException(GenAiLibraryError, + "The OpenVINO GenAI C API library does not export '" & name & + "'; it may not match GenAI 2026.4.1.0.") + err.symbol = name + err.attempted = candidateGenAiLibraries() + raise err + result = address + +proc missingGenAiSymbols*(names: openArray[string]): seq[string] = + let handle = genAiLibrary() + result = @[] + for name in names: + if handle.symAddr(name.cstring) == nil: + result.add(name) + +macro genaiImport*(procedure: untyped): untyped = + ## Lazily resolves a declaration by its upstream C name. + procedure.expectKind(nnkProcDef) + if procedure.body.kind != nnkEmpty: + error("genaiImport expects a declaration without a body", procedure) + + let + nameNode = procedure.name + plainName = if nameNode.kind == nnkPostfix: nameNode[1] else: nameNode + symbolName = newLit($plainName) + cache = genSym(nskVar, $plainName & "Symbol") + signature = nnkProcTy.newTree(procedure.params.copyNimTree, + nnkPragma.newTree(ident("cdecl"))) + + var call = nnkCall.newTree(cache) + for index in 1 ..< procedure.params.len: + let parameter = procedure.params[index] + for nameIndex in 0 .. parameter.len - 3: + let argument = parameter[nameIndex] + call.add(if argument.kind == nnkPostfix: argument[1] else: argument) + + let returnsValue = procedure.params[0].kind != nnkEmpty + let forward = if returnsValue: nnkAsgn.newTree(ident("result"), call) + else: call + + # invariant: the function pointer type is built from this C declaration, + # and the loader refuses a missing symbol before that pointer is called. + procedure.body = quote do: + if `cache` == nil: + `cache` = cast[`signature`](genAiFunctionSymbol(`symbolName`)) + `forward` + + result = newStmtList( + nnkVarSection.newTree( + nnkIdentDefs.newTree(cache, signature, newNilLit())), + procedure) diff --git a/src/openvino/tensor.nim b/src/openvino/tensor.nim index 044339e..3e003bb 100644 --- a/src/openvino/tensor.nim +++ b/src/openvino/tensor.nim @@ -24,29 +24,36 @@ import shape export shape -type Tensor* = object - ## A tensor and its storage. - ## - ## Owns one `ov_tensor_t`. Copying a `Tensor` shares the same native object - ## and the same closed state, so closing through one copy closes all of them; - ## see `docs/decisions/0002-handle-model.md`. - ## - ## Threads: a tensor is mutable storage with no lock, so sharing one across - ## threads is the caller's problem entirely. Two threads writing through - ## `copyFrom`, or one writing while another calls `setShape`, is a data race - ## on the storage and, after a reshape, possibly on a freed buffer. Give each - ## thread its own tensor. - handle: Handle[ov_tensor_t] - ownsStorage: bool +type + StorageOwnership* = enum + ## What the wrapper can establish about the storage, not the C handle. + soUnknown + soOpenVinoOwned + soCallerOwned + + Tensor* = object + ## A tensor and its storage. + ## + ## Owns one `ov_tensor_t`. Copying a `Tensor` shares the same native object + ## and the same closed state, so closing through one copy closes all of them; + ## see `docs/decisions/0002-handle-model.md`. + ## + ## Threads: a tensor is mutable storage with no lock, so sharing one across + ## threads is the caller's problem entirely. Two threads writing through + ## `copyFrom`, or one writing while another calls `setShape`, is a data race + ## on the storage and, after a reshape, possibly on a freed buffer. Give each + ## thread its own tensor. + handle: Handle[ov_tensor_t] + storageOwnership: StorageOwnership proc releaseTensor(native: ptr ov_tensor_t) {.nimcall.} = ## Release function handed to the handle model. ov_tensor_free(native) -proc wrap(native: ptr ov_tensor_t; ownsStorage: bool): Tensor = +proc wrap(native: ptr ov_tensor_t; ownership: StorageOwnership): Tensor = ## Takes ownership of `native`. Only called after a successful create. Tensor(handle: newHandle(native, releaseTensor, "tensor"), - ownsStorage: ownsStorage) + storageOwnership: ownership) template withRawShape(shapeValue: Shape; rawName: untyped; body: untyped) = ## Builds an `ov_shape_t` for `shapeValue`, runs `body`, then releases it. @@ -78,6 +85,13 @@ proc close*(tensor: Tensor) = ## invalid afterwards. tensor.handle.close() +proc unsafeNativeHandle*(tensor: Tensor): ptr ov_tensor_t = + ## Returns the borrowed C tensor handle for APIs such as GenAI VLM. + ## + ## The pointer is valid only while this tensor remains open. Do not release + ## it, retain it after the call, or use it after `close()`. + tensor.handle.native() + proc isClosed*(tensor: Tensor): bool = ## Reports whether the tensor has been closed. Never raises. tensor.handle.isClosed() @@ -94,7 +108,7 @@ proc newTensor*(elementType: ElementType; tensorShape: Shape): Tensor = withRawShape(tensorShape, raw): checkStatus(ov_tensor_create(elementType.toRaw(), raw, addr native), "create tensor", $elementType & " " & $tensorShape) - result = wrap(native, ownsStorage = true) + result = wrap(native, soOpenVinoOwned) proc elementType*(tensor: Tensor): ElementType = ## Returns the tensor's element type. @@ -294,23 +308,30 @@ proc unsafeTensorFromPointer*(elementType: ElementType; tensorShape: Shape; addr native), "create tensor over borrowed memory", $elementType & " " & $tensorShape) - result = wrap(native, ownsStorage = false) + result = wrap(native, soCallerOwned) + +proc storageOwnership*(tensor: Tensor): StorageOwnership = + ## Reports whether the storage is known to be OpenVINO- or caller-owned. + ## Request-returned tensors have unknown ownership: their bindings can have + ## been replaced, including through the raw API. Never infer that caller + ## memory may be freed from an unknown result. + tensor.storageOwnership proc ownsStorage*(tensor: Tensor): bool = ## Reports whether OpenVINO allocated this tensor's storage. ## - ## False only for a tensor made by `unsafeTensorFromPointer`, whose storage - ## belongs to the caller. Useful in assertions and diagnostics. - tensor.ownsStorage + ## False also means ownership is unknown; use `storageOwnership` to + ## distinguish this from caller-owned storage. + tensor.storageOwnership == soOpenVinoOwned proc wrapOwnedTensor*(native: ptr ov_tensor_t): Tensor = ## Takes ownership of a tensor handle that OpenVINO returned. ## ## Internal to the package. Used for the handles that ## `ov_infer_request_get_*_tensor_by_index` produces, which the caller owns - ## and must release even though the storage behind them belongs to the - ## request. - wrap(native, ownsStorage = true) + ## and must release. Their storage may be owned by OpenVINO or by the caller; + ## the C handle alone does not establish which. + wrap(native, soUnknown) proc unsafeRawHandle*(tensor: Tensor): ptr ov_tensor_t = ## Returns the borrowed native handle, for interoperating with code that uses diff --git a/src/openvino/version.nim b/src/openvino/version.nim index 84adfd6..35353b6 100644 --- a/src/openvino/version.nim +++ b/src/openvino/version.nim @@ -39,7 +39,7 @@ const ## `RepositoryName`; the Nimble package identifier and Nim import root are ## both `openvino`, because Nimble identifiers may not contain a hyphen. - PackageVersion* = "0.2.1" + PackageVersion* = "0.2.2" ## SemVer version of this Nim package. Versioned independently of the ## OpenVINO runtime: see `TargetOpenVinoVersion`. diff --git a/tests/genai/tgenai_integration.nim b/tests/genai/tgenai_integration.nim new file mode 100644 index 0000000..1a3e080 --- /dev/null +++ b/tests/genai/tgenai_integration.nim @@ -0,0 +1,248 @@ +# SPDX-License-Identifier: Apache-2.0 + +## End-to-end GenAI checks using locally installed C APIs and models. +## +## Set OPENVINO_GENAI_TEST_MODEL to an OpenVINO LLM model directory, +## OPENVINO_GENAI_TEST_WHISPER_MODEL to an OpenVINO Whisper model directory, +## OPENVINO_GENAI_TEST_AUDIO_F32 to mono 16 kHz float32 PCM samples, and make +## the OpenVINO Runtime, GenAI and Tokenizers libraries discoverable. + +import std/[os, strutils, unittest] + +import openvino +import openvino/raw/genai as rawGenAi + +const expectedSymbols = rawGenAi.GenAiApiSymbols + +proc loadFloatSamples(path: string): seq[float32] = + let byteCount = getFileSize(path) + if byteCount <= 0 or byteCount mod int64(sizeof(float32)) != 0: + raise newException(ValueError, + "audio sample file must contain raw float32 PCM samples") + var file: File + if not file.open(path, fmRead): + raise newException(IOError, "cannot open audio samples: " & path) + defer: file.close() + result = newSeq[float32](int(byteCount div int64(sizeof(float32)))) + let readCount = file.readBuffer(addr result[0], int(byteCount)) + if readCount != int(byteCount): + raise newException(IOError, "audio sample file was truncated while reading") + +suite "OpenVINO GenAI C API": + test "all pinned C header symbols are exported by the installed library": + let missing = rawGenAi.missingGenAiSymbols(expectedSymbols) + checkpoint("missing symbols: " & $missing) + check missing.len == 0 + + test "JSON and chat history manage owned C handles": + let message = jsonFromString("""{"role":"user","content":"hello"}""") + check "hello" in message.toJson() + check newJsonObject().toJson() == "{}" + check newJsonArray().toJson() == "[]" + check message.copy().toJson() == message.toJson() + let history = newChatHistory() + history.pushBack(message) + check history.len() == 1 + check not history.isEmpty() + check "hello" in history.firstMessage().toJson() + check "hello" in history.messageAt(0).toJson() + check "hello" in history.messages().toJson() + check "hello" in history.lastMessage().toJson() + let tools = jsonFromString("""[{"type":"function"}]""") + history.setTools(tools) + check history.tools().toJson() == tools.toJson() + let context = jsonFromString("""{"trace":"test"}""") + history.setExtraContext(context) + check history.extraContext().toJson() == context.toJson() + let fromJson = chatHistoryFromJson(jsonFromString( + """[{"role":"user","content":"from array"}]""")) + check fromJson.len() == 1 + check "from array" in fromJson.firstMessage().toJson() + history.popBack() + check history.isEmpty() + history.pushBack(message) + history.clear() + check history.isEmpty() + + test "generation configuration accepts and validates settings": + let config = newGenerationConfig() + config.setMaxNewTokens(8) + config.setDoSample(false) + config.setTemperature(0.0) + config.setStopStrings(["", "###"]) + config.setStopStrings([]) # clearing an array must pass a non-null C pointer + config.setStopCriteria(scEarly) + config.validate() + check config.maxNewTokens() == 8 + + let allSettings = newGenerationConfig() + allSettings.setMaxLength(128) + allSettings.setMinNewTokens(1) + allSettings.setIgnoreEos(false) + allSettings.setEcho(false) + allSettings.setLogprobs(1) + allSettings.setIncludeStopString(true) + allSettings.setStopTokenIds([2'i64]) + allSettings.setNumBeamGroups(1) + allSettings.setNumBeams(1) + allSettings.setDiversityPenalty(0.0) + allSettings.setLengthPenalty(1.0) + allSettings.setNumReturnSequences(1) + allSettings.setNoRepeatNgramSize(0) + allSettings.setTopP(1.0) + allSettings.setTopK(40) + allSettings.setMinP(0.0) + allSettings.setRepetitionPenalty(1.0) + allSettings.setPresencePenalty(0.0) + allSettings.setFrequencyPenalty(0.0) + allSettings.setRngSeed(42) + allSettings.setAssistantConfidenceThreshold(0.5) + allSettings.setNumAssistantTokens(3) + allSettings.setMaxNgramSize(3) + allSettings.setEosTokenId(2) + + test "LLM text, history, streaming, properties and metrics work on CPU": + let modelPath = getEnv("OPENVINO_GENAI_TEST_MODEL") + check modelPath.len > 0 + let jsonConfig = generationConfigFromJson(modelPath / "generation_config.json") + jsonConfig.setMaxNewTokens(8) + check jsonConfig.maxNewTokens() == 8 + let config = newGenerationConfig() + config.setMaxNewTokens(8) + config.setDoSample(false) + let pipeline = newLlmPipeline(modelPath, "CPU", @[ + ("PERFORMANCE_HINT", "LATENCY")]) + pipeline.setGenerationConfig(config) + check pipeline.generationConfig().maxNewTokens() == 8 + pipeline.startChat() + pipeline.finishChat() + + let response = pipeline.generate("Say hello in one word.", config) + check response.text().len > 0 + let metrics = response.generationMetrics() + check metrics.generatedTokenCount() > 0 + discard metrics.loadTime() + discard metrics.inputTokenCount() + discard metrics.timeToFirstToken() + discard metrics.timePerOutputToken() + discard metrics.throughput() + discard metrics.inputTimePerToken() + discard metrics.inferenceDuration() + discard metrics.generationDuration() + discard metrics.tokenizationDuration() + discard metrics.detokenizationDuration() + discard metrics.chatTemplateDuration() + + var streamed = "" + let complete = pipeline.streamGenerate("Say hi.", proc (piece: string): + StreamAction = + streamed.add(piece) + streamContinue, config) + check complete.len > 0 + check complete == streamed + + var pieceCount = 0 + let stopped = pipeline.streamGenerate("Say hello.", proc (_: string): + StreamAction = + inc pieceCount + streamStop, config) + check pieceCount > 0 + check pieceCount < 8 + check stopped.len > 0 + + var cancelledPieces = 0 + let cancelled = pipeline.streamGenerate("Say hello.", proc (_: string): + StreamAction = + inc cancelledPieces + streamCancel, config) + check cancelledPieces > 0 + check cancelled.len > 0 + + var callbackErrorWasRethrown = false + try: + discard pipeline.streamGenerate("Say hello.", proc (_: string): + StreamAction = + raise newException(ValueError, "stream callback failed"), config) + except GenAiCallbackError as error: + callbackErrorWasRethrown = + error.callbackMessage == "stream callback failed" + check callbackErrorWasRethrown + + let history = newChatHistory() + history.pushBack(jsonFromString( + """{"role":"user","content":"Answer with one word: yes"}""")) + let historyResult = pipeline.generate(history, config) + check historyResult.text().len > 0 + metrics.addInPlace(historyResult.generationMetrics()) + check pipeline.streamGenerate(history, proc (piece: string): StreamAction = + streamContinue, config).len > 0 + + test "Whisper configuration, timestamps, scores and metrics work on CPU": + let modelPath = getEnv("OPENVINO_GENAI_TEST_WHISPER_MODEL") + let audioPath = getEnv("OPENVINO_GENAI_TEST_AUDIO_F32") + check modelPath.len > 0 + check audioPath.len > 0 + let modelConfigPath = modelPath / "generation_config.json" + if fileExists(modelConfigPath): + let loadedConfig = whisperGenerationConfigFromJson(modelConfigPath) + check loadedConfig.decoderStartTokenId() == 50258 + check loadedConfig.maxInitialTimestampIndex() == 50 + let samples = loadFloatSamples(audioPath) + let config = newWhisperGenerationConfig() + config.setLanguage("en") + config.setTask("transcribe") + config.setReturnTimestamps(true) + check config.language() == "en" + check config.task() == "transcribe" + check config.returnTimestamps() + + let pipeline = newWhisperPipeline(modelPath) + let result = pipeline.transcribe(samples, config) + config.setInitialPrompt("Use clear punctuation.") + config.setHotwords("OpenVINO") + check config.initialPrompt() == "Use clear punctuation." + check config.hotwords() == "OpenVINO" + check result.transcriptionCount() == 1 + check "How are you doing today?" in result.transcription() + check result.hasChunks() + check result.chunkCount() > 0 + let chunk = result.chunkAt(0) + check "How are you doing today?" in chunk.chunkText() + check chunk.chunkTimestamps().endTime > chunk.chunkTimestamps().startTime + let metrics = result.generationMetrics() + check metrics.generatedTokenCount() > 0 + discard result.text() + discard result.score(0) + discard metrics.loadTime() + discard metrics.inputTokenCount() + discard metrics.timeToFirstToken() + discard metrics.timePerOutputToken() + discard metrics.throughput() + discard metrics.inputTimePerToken() + discard metrics.inferenceDuration() + discard metrics.generationDuration() + discard metrics.tokenizationDuration() + discard metrics.detokenizationDuration() + discard metrics.chatTemplateDuration() + + config.setIsMultilingual(true) + config.setPreviousStartTokenId(50361) + config.setNoTimestampsTokenId(50363) + config.setDecoderStartTokenId(50258) + config.setPadTokenId(50257) + config.setTranslateTokenId(50358) + config.setTranscribeTokenId(50359) + config.setMaxInitialTimestampIndex(50) + config.setBeginSuppressTokens([220'i64, 50257'i64]) + config.setSuppressTokens([1'i64, 2'i64, 7'i64]) + check config.multilingual() + check config.previousStartTokenId() == 50361 + check config.noTimestampsTokenId() == 50363 + check config.decoderStartTokenId() == 50258 + check config.padTokenId() == 50257 + check config.translateTokenId() == 50358 + check config.transcribeTokenId() == 50359 + check config.maxInitialTimestampIndex() == 50 + check config.beginSuppressTokens() == @[220'i64, 50257'i64] + check config.suppressTokens() == @[1'i64, 2'i64, 7'i64] + pipeline.setGenerationConfig(pipeline.generationConfig()) diff --git a/tests/integration/tcpu_inference.nim b/tests/integration/tcpu_inference.nim index 76673f1..b173528 100644 --- a/tests/integration/tcpu_inference.nim +++ b/tests/integration/tcpu_inference.nim @@ -595,6 +595,7 @@ suite "external buffers and the unsafe path": let value = newTensor(etF32, initShape(1, 4)) defer: value.close() check value.ownsStorage() + check value.storageOwnership == soOpenVinoOwned test "tensorFrom copies, so the source may change afterwards": var source = @[float32(1), 2, 3, 4] @@ -617,6 +618,7 @@ suite "external buffers and the unsafe path": let value = unsafeTensorFromPointer(etF32, initShape(1, 4), buffer) defer: value.close() check not value.ownsStorage() + check value.storageOwnership == soCallerOwned check value.toSeq(float32) == @[float32(0), 1, 2, 3] # Writing through the caller's own pointer is visible to the tensor. That is @@ -646,6 +648,10 @@ suite "external buffers and the unsafe path": let input = unsafeTensorFromPointer(etF32, initShape(1, 4), buffer) request.setInputTensor(0, input) + let returned = request.inputTensor(0) + check returned.storageOwnership == soUnknown + check not returned.ownsStorage + returned.close() request.infer() let output = request.outputTensor(0) check output.toSeq(float32) == @[float32(0.0), 2.0, 0.0, 4.0] @@ -658,6 +664,32 @@ suite "external buffers and the unsafe path": request.close() check buffer[1] == 2.0 + test "request-returned tensors report unknown ownership after rebinding": + var buffer = [float32(1), 2, 3, 4] + let core = newCore() + defer: core.close() + let compiled = core.compileModel(modelPath, device) + defer: compiled.close() + let request = compiled.createInferRequest() + defer: request.close() + let owned = tensorFrom(etF32, initShape(1, 4), buffer) + defer: owned.close() + let external = unsafeTensorFromPointer(etF32, initShape(1, 4), + addr buffer[0]) + defer: external.close() + for value in [owned, external, owned]: + request.setInputTensor("input", value) + let returned = request.inputTensor(0) + check returned.storageOwnership == soUnknown + check not returned.ownsStorage + check returned.toSeq(float32) == @buffer + returned.close() + request.infer() + let output = request.outputTensor(0) + defer: output.close() + check output.storageOwnership == soUnknown + check not output.ownsStorage + test "closing an unsafe tensor does not free the caller's buffer": # Made observable by writing through the pointer after the tensor is gone. # Under a wrong release this is a use-after-free, which is what the test is diff --git a/tests/packaging/consumer.nim b/tests/packaging/consumer.nim index 91c467f..b7808f2 100644 --- a/tests/packaging/consumer.nim +++ b/tests/packaging/consumer.nim @@ -16,6 +16,7 @@ import std/os import openvino +import openvino/raw/genai as rawGenAi proc main() = if paramCount() < 1: @@ -25,6 +26,8 @@ proc main() = echo "package : ", PackageName, " ", PackageVersion echo "targets : OpenVINO ", TargetOpenVinoVersion + echo "GenAI C symbols: ", rawGenAi.GenAiApiSymbols.len + echo "GenAI stays unloaded: ", default(LlmPipeline).isClosed() let version = runtimeVersion() echo "runtime : ", version.build diff --git a/tests/unit/tgenai_surface.nim b/tests/unit/tgenai_surface.nim new file mode 100644 index 0000000..9121bce --- /dev/null +++ b/tests/unit/tgenai_surface.nim @@ -0,0 +1,46 @@ +# SPDX-License-Identifier: Apache-2.0 + +## Compile-only contract tests for the optional GenAI surface. +## +## Importing either public entry point must not attempt to load optional native +## libraries. Native behaviour is covered by `nimble testGenAi`. + +import std/unittest + +import openvino +import openvino/raw/genai as rawGenAi + +suite "optional GenAI public surface": + test "the managed import remains available without GenAI loading": + check PackageVersion.len > 0 + + test "the streaming statuses match the C ABI values": + check int(rawGenAi.OV_GENAI_STREAMING_STATUS_RUNNING) == 0 + check int(rawGenAi.OV_GENAI_STREAMING_STATUS_STOP) == 1 + check int(rawGenAi.OV_GENAI_STREAMING_STATUS_CANCEL) == 2 + + test "the complete upstream C symbol list includes constructors": + check rawGenAi.GenAiApiSymbols.len == 153 + check "ov_genai_llm_pipeline_create" in rawGenAi.GenAiApiSymbols + check "ov_genai_vlm_pipeline_create" in rawGenAi.GenAiApiSymbols + check "ov_genai_whisper_pipeline_create" in rawGenAi.GenAiApiSymbols + + test "the optional loader has platform candidates without loading them": + check rawGenAi.candidateGenAiLibraries().len > 0 + + test "managed GenAI rejects embedded NUL before loading native libraries": + expect OpenVinoArgumentError: + discard newLlmPipeline("model\0truncated") + expect OpenVinoArgumentError: + discard newLlmPipeline("model", "CPU", @[("bad\0key", "value")]) + expect OpenVinoArgumentError: + discard newLlmPipeline("model", "CPU", + newSeq[(string, string)](17)) + expect OpenVinoArgumentError: + discard default(LlmPipeline).generate("prompt\0truncated") + expect OpenVinoArgumentError: + discard jsonFromString("{}\0truncated") + expect OpenVinoArgumentError: + default(WhisperGenerationConfig).setLanguage("en\0truncated") + expect OpenVinoArgumentError: + default(GenerationConfig).setStopStrings(["bad\0stop"])