feat: initial llm-chat v0.1.0 (llm.chat@0.1.0)
All checks were successful
CI / Linux x86_64 (Forgejo) (push) Successful in 1m57s

Generic Ollama-compatible LLM chat adapter. The lower-level
counterpart to orchestrator-llm: orchestrator-llm wraps the LLM
in a planning prompt that emits a structured F∆I Plan; this
module is the plain-prompt adapter that flows compose for
summarisation, translation, free-form Q&A, etc.

Capability surface:

  Inputs:
    prompt        : text
    endpoint      : text   (Ollama /api/chat URL)
    model         : text
    api_key       : text   (optional bearer token)
    system_prompt : text   (optional)

  Outputs:
    response       : text   (assistant reply)
    model_endpoint : text   (audit correlation)
    model_name     : text   (audit correlation)
    model_digest   : text   (Ollama /api/show probe; empty
                              for non-Ollama or transient failures)

  Permissions: net to localhost / 127.0.0.1 / api.openai.com /
               api.anthropic.com.

The audit-field trio (endpoint + name + digest) closes the same
forensic gap that orchestrator-llm v0.3.1 closed for plan
generation: any historical chat invocation can be traced to the
exact model that produced it.

Implementation reuses the same defensive Ollama client pattern
from orchestrator-llm — derive_show_url + extract_show_digest
+ best-effort probe_model_digest. Duplication accepted at the
two-module mark; a shared crate refactor lands once a third
module needs the same plumbing.

12 host-side tests cover prompt building, Ollama-shaped
response parsing, URL transform, digest extraction (top-level
+ nested), end-to-end success, end-to-end probe-failure
swallow, end-to-end skip-for-non-Ollama, and the missing-input
guards.

Wasm artifact: 294 KB. Verified to build with v1.0 fai:platform
imports baked in.

Bootstrapped via 'fai new module llm.chat' (workspace v0.10.13)
which now produces an SDK-based template directly.

Signed-off-by: flemming-it <sf@flemming.it>
This commit is contained in:
flemming-it 2026-05-03 23:17:36 +02:00
commit 4c10a5ff3d
11 changed files with 1419 additions and 0 deletions

85
.forgejo/workflows/ci.yml Normal file
View file

@ -0,0 +1,85 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
CARGO_TERM_COLOR: always
RUSTFLAGS: "-D warnings"
RUST_TOOLCHAIN: "1.86"
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
jobs:
ci:
name: Linux x86_64 (Forgejo)
runs-on: ubuntu-latest
steps:
# Manual external-URL checkout — see fai/platform CI for
# background. Lays this repo at $GITHUB_WORKSPACE.
- name: Checkout text-extract via external URL
run: |
set -eu
mkdir -p "$GITHUB_WORKSPACE"
cd "$GITHUB_WORKSPACE"
git init -q
git remote add origin \
"https://x-access-token:${GITHUB_TOKEN}@git.flemming.ws/${GITHUB_REPOSITORY}.git"
git fetch --depth=1 origin "$GITHUB_SHA"
git checkout -q FETCH_HEAD
# The fai-module-sdk dependency is a git dep against a repo
# that lives in another Forgejo org. The repo-scoped
# GITHUB_TOKEN cannot read it, and the Forgejo instance has
# REQUIRE_SIGNIN_VIEW=true so anonymous read is also denied.
# MODULE_SDK_PAT is a stored secret with read access to
# fai/module-sdk; we inject it into any outgoing
# https://git.flemming.ws/ URL via insteadOf so cargo's git
# fetch (driven by CARGO_NET_GIT_FETCH_WITH_CLI) authenticates
# transparently.
- name: Configure git URL rewrite for SDK fetch
env:
SDK_PAT: ${{ secrets.MODULE_SDK_PAT }}
run: |
git config --global \
"url.https://x-access-token:${SDK_PAT}@git.flemming.ws/.insteadOf" \
"https://git.flemming.ws/"
- name: Install system dependencies
run: |
apt-get update -qq
apt-get install -y --no-install-recommends \
curl \
ca-certificates \
build-essential \
pkg-config \
libssl-dev \
git
- name: Install Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y \
--profile minimal \
--default-toolchain "$RUST_TOOLCHAIN" \
--target wasm32-wasip2 \
--component rustfmt \
--component clippy
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Cargo fmt --check
run: cargo fmt --all -- --check
- name: Cargo clippy
run: cargo clippy --all-targets -- -D warnings
- name: Cargo build (host)
run: cargo build --all-targets
- name: Cargo test (host)
run: cargo test --all-targets
- name: Cargo build (wasm32-wasip2)
run: cargo build --release --target wasm32-wasip2

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
target/
Cargo.lock.bak
.DS_Store

638
Cargo.lock generated Normal file
View file

@ -0,0 +1,638 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "ahash"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
name = "anyhow"
version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "bitflags"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
[[package]]
name = "bytes"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "fai-module-sdk"
version = "0.1.2"
source = "git+https://git.flemming.ws/fai/module-sdk.git?branch=main#f209fbc86f531b53e576f3cdbdf75750eef3b07a"
dependencies = [
"fai-module-sdk-macros",
"serde",
"serde_json",
"thiserror",
"wit-bindgen 0.36.0",
]
[[package]]
name = "fai-module-sdk-macros"
version = "0.1.2"
source = "git+https://git.flemming.ws/fai/module-sdk.git?branch=main#f209fbc86f531b53e576f3cdbdf75750eef3b07a"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
]
[[package]]
name = "hashbrown"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "http"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"
dependencies = [
"bytes",
"itoa",
]
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "indexmap"
version = "2.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
dependencies = [
"equivalent",
"hashbrown 0.17.0",
"serde",
"serde_core",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "leb128"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6cc46bac87ef8093eed6f272babb833b6443374399985ac8ed28471ee0918545"
[[package]]
name = "llm_chat"
version = "0.1.0"
dependencies = [
"fai-module-sdk",
"serde",
"serde_json",
"thiserror",
"waki",
]
[[package]]
name = "log"
version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "memchr"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "smallvec"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
[[package]]
name = "spdx"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3"
dependencies = [
"smallvec",
]
[[package]]
name = "syn"
version = "2.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "waki"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2db2daf1dfbadf228fd8b3c22b96a359135fd673b3d2c203274ee6a0df9c77"
dependencies = [
"anyhow",
"form_urlencoded",
"http",
"serde",
"waki-macros",
"wit-bindgen 0.34.0",
]
[[package]]
name = "waki-macros"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a061143f321cc5eeb523f60bdbcd45cfc3ee8851f8cf24f7a4b963bddc5642eb"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "wasm-encoder"
version = "0.219.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8aa79bcd666a043b58f5fa62b221b0b914dd901e6f620e8ab7371057a797f3e1"
dependencies = [
"leb128",
"wasmparser 0.219.2",
]
[[package]]
name = "wasm-encoder"
version = "0.220.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e913f9242315ca39eff82aee0e19ee7a372155717ff0eb082c741e435ce25ed1"
dependencies = [
"leb128",
"wasmparser 0.220.1",
]
[[package]]
name = "wasm-metadata"
version = "0.219.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1ef51bd442042a2a7b562dddb6016ead52c4abab254c376dcffc83add2c9c34"
dependencies = [
"anyhow",
"indexmap",
"serde",
"serde_derive",
"serde_json",
"spdx",
"wasm-encoder 0.219.2",
"wasmparser 0.219.2",
]
[[package]]
name = "wasm-metadata"
version = "0.220.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "185dfcd27fa5db2e6a23906b54c28199935f71d9a27a1a27b3a88d6fee2afae7"
dependencies = [
"anyhow",
"indexmap",
"serde",
"serde_derive",
"serde_json",
"spdx",
"wasm-encoder 0.220.1",
"wasmparser 0.220.1",
]
[[package]]
name = "wasmparser"
version = "0.219.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5220ee4c6ffcc0cb9d7c47398052203bc902c8ef3985b0c8134118440c0b2921"
dependencies = [
"ahash",
"bitflags",
"hashbrown 0.14.5",
"indexmap",
"semver",
]
[[package]]
name = "wasmparser"
version = "0.220.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d07b6a3b550fefa1a914b6d54fc175dd11c3392da11eee604e6ffc759805d25"
dependencies = [
"ahash",
"bitflags",
"hashbrown 0.14.5",
"indexmap",
"semver",
]
[[package]]
name = "wit-bindgen"
version = "0.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e11ad55616555605a60a8b2d1d89e006c2076f46c465c892cc2c153b20d4b30"
dependencies = [
"wit-bindgen-rt 0.34.0",
"wit-bindgen-rust-macro 0.34.0",
]
[[package]]
name = "wit-bindgen"
version = "0.36.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a2b3e15cd6068f233926e7d8c7c588b2ec4fb7cc7bf3824115e7c7e2a8485a3"
dependencies = [
"wit-bindgen-rt 0.36.0",
"wit-bindgen-rust-macro 0.36.0",
]
[[package]]
name = "wit-bindgen-core"
version = "0.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "163cee59d3d5ceec0b256735f3ab0dccac434afb0ec38c406276de9c5a11e906"
dependencies = [
"anyhow",
"heck",
"wit-parser 0.219.2",
]
[[package]]
name = "wit-bindgen-core"
version = "0.36.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b632a5a0fa2409489bd49c9e6d99fcc61bb3d4ce9d1907d44662e75a28c71172"
dependencies = [
"anyhow",
"heck",
"wit-parser 0.220.1",
]
[[package]]
name = "wit-bindgen-rt"
version = "0.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "744845cde309b8fa32408d6fb67456449278c66ea4dcd96de29797b302721f02"
dependencies = [
"bitflags",
]
[[package]]
name = "wit-bindgen-rt"
version = "0.36.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7947d0131c7c9da3f01dfde0ab8bd4c4cf3c5bd49b6dba0ae640f1fa752572ea"
dependencies = [
"bitflags",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6919521fc7807f927a739181db93100ca7ed03c29509b84d5f96b27b2e49a9a"
dependencies = [
"anyhow",
"heck",
"indexmap",
"prettyplease",
"syn",
"wasm-metadata 0.219.2",
"wit-bindgen-core 0.34.0",
"wit-component 0.219.2",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.36.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4329de4186ee30e2ef30a0533f9b3c123c019a237a7c82d692807bf1b3ee2697"
dependencies = [
"anyhow",
"heck",
"indexmap",
"prettyplease",
"syn",
"wasm-metadata 0.220.1",
"wit-bindgen-core 0.36.0",
"wit-component 0.220.1",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c967731fc5d50244d7241ecfc9302a8929db508eea3c601fbc5371b196ba38a5"
dependencies = [
"anyhow",
"prettyplease",
"proc-macro2",
"quote",
"syn",
"wit-bindgen-core 0.34.0",
"wit-bindgen-rust 0.34.0",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.36.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "177fb7ee1484d113b4792cc480b1ba57664bbc951b42a4beebe573502135b1fc"
dependencies = [
"anyhow",
"prettyplease",
"proc-macro2",
"quote",
"syn",
"wit-bindgen-core 0.36.0",
"wit-bindgen-rust 0.36.0",
]
[[package]]
name = "wit-component"
version = "0.219.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b8479a29d81c063264c3ab89d496787ef78f8345317a2dcf6dece0f129e5fcd"
dependencies = [
"anyhow",
"bitflags",
"indexmap",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder 0.219.2",
"wasm-metadata 0.219.2",
"wasmparser 0.219.2",
"wit-parser 0.219.2",
]
[[package]]
name = "wit-component"
version = "0.220.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b505603761ed400c90ed30261f44a768317348e49f1864e82ecdc3b2744e5627"
dependencies = [
"anyhow",
"bitflags",
"indexmap",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder 0.220.1",
"wasm-metadata 0.220.1",
"wasmparser 0.220.1",
"wit-parser 0.220.1",
]
[[package]]
name = "wit-parser"
version = "0.219.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca004bb251010fe956f4a5b9d4bf86b4e415064160dd6669569939e8cbf2504f"
dependencies = [
"anyhow",
"id-arena",
"indexmap",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-xid",
"wasmparser 0.219.2",
]
[[package]]
name = "wit-parser"
version = "0.220.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae2a7999ed18efe59be8de2db9cb2b7f84d88b27818c79353dfc53131840fe1a"
dependencies = [
"anyhow",
"id-arena",
"indexmap",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-xid",
"wasmparser 0.220.1",
]
[[package]]
name = "zerocopy"
version = "0.8.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"

49
Cargo.toml Normal file
View file

@ -0,0 +1,49 @@
# Standalone Cargo.toml — targets wasm32-wasip2.
#
# Build with:
# cargo build --release --target wasm32-wasip2
[package]
name = "llm_chat"
version = "0.1.0"
edition = "2024"
license = "Apache-2.0"
publish = false
description = "F∆I module providing llm.chat"
[lib]
# cdylib for the wasm artifact, rlib so integration tests can
# link against the module's `invoke` function on the host.
crate-type = ["cdylib", "rlib"]
[dependencies]
fai-module-sdk = { git = "https://git.flemming.ws/fai/module-sdk.git", branch = "main" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
# WASI-0.2 HTTP client. Only compiled into the wasm32-wasip2 build.
[target.'cfg(target_arch = "wasm32")'.dependencies]
waki = "0.5"
[dev-dependencies]
serde_json = "1"
[profile.release]
opt-level = "s"
lto = true
codegen-units = 1
strip = "symbols"
[lints.rust]
unsafe_op_in_unsafe_fn = "warn"
[lints.clippy]
unwrap_used = "deny"
expect_used = "deny"
panic = "deny"
print_stdout = "deny"
print_stderr = "deny"
[workspace]
# Empty so this package is NOT picked up by a parent.

73
LICENSE Normal file
View file

@ -0,0 +1,73 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2026 fai-modules
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

14
NOTICE Normal file
View file

@ -0,0 +1,14 @@
llm-chat
Copyright 2026 Flemming.AI
This product includes software developed by Dr. Stefan Flemming
and contributors (https://flemming.ai/).
------------------------------------------------------------------
Third-party acknowledgments
The Ollama-compatible chat client uses the `waki` (wasi-http)
crate on the wasm32 target plus the `serde` and `quick-xml`
ecosystem on the host build. Runtime dependencies and their
licenses are documented in the Software Bill of Materials (SBOM)
generated on every release.

62
README.md Normal file
View file

@ -0,0 +1,62 @@
# llm-chat
F∆I module providing the `llm.chat` capability — a generic
Ollama-compatible LLM chat adapter.
## Capability
| Field | Value |
|-------|-------|
| Capability | `llm.chat@0.1.0` |
| Inputs | `prompt: text`, `endpoint: text`, `model: text`, `api_key: text` (opt), `system_prompt: text` (opt) |
| Outputs | `response: text`, `model_endpoint: text`, `model_name: text`, `model_digest: text` |
| Permissions | `net: localhost`, `net: 127.0.0.1`, `net: api.openai.com`, `net: api.anthropic.com` |
| Status (in store index) | `alpha` |
## Why a separate module from orchestrator-llm
`orchestrator-llm` wraps an LLM call inside a planning prompt
that emits a structured F∆I `Plan`. `llm.chat` is the lower-
level adapter: it sends a prompt and returns the assistant text
verbatim. Flows that need a generic chat step (summarisation,
translation, free-form Q&A) compose `llm.chat` directly; flows
that need plan generation use `orchestrator-llm`.
## Audit fields
`model_endpoint`, `model_name`, and `model_digest` are emitted
on every successful invocation. Together they answer the audit
question "which exact model produced this response?" The digest
probe targets Ollama's `/api/show` and is best-effort — non-
Ollama endpoints and transient probe failures yield an empty
digest rather than blocking the response. Cf. F∆I Platform
`docs/advanced/compliance-gaps.md` Gap 1.
## Build
```bash
cargo build --release --target wasm32-wasip2
```
## Test
```bash
cargo test # 11 tests, all host-side
cargo build --release --target wasm32-wasip2
```
## SDK source
The Cargo.toml git-deps `fai-module-sdk` from
`https://git.flemming.ws/fai/module-sdk.git`. The Forgejo
instance has `REQUIRE_SIGNIN_VIEW=true`, so anonymous clones
fail; CI uses the `MODULE_SDK_PAT` actions secret + `git config
url.X.insteadOf Y` to authenticate cargo's git fetch
transparently. Local dev uses the same pattern via env vars.
## License
Apache-2.0.
Author: Dr. Stefan Flemming, Flemming.AI <platform@flemming.ai>
Repository: https://git.flemming.ws/fai-modules/llm-chat

54
module.yaml Normal file
View file

@ -0,0 +1,54 @@
schema_version: 1
name: llm-chat
version: 0.1.0
# Capability provided by this module.
provides:
- capability: llm.chat
version: 0.1.0
# Inputs the invoke function accepts.
inputs:
# The user-facing prompt text.
prompt: text
# Ollama-shaped /api/chat endpoint, e.g.
# "http://localhost:11434/api/chat".
endpoint: text
# Model identifier as registered with the endpoint, e.g.
# "qwen2.5:14b" or "llama3.1:8b".
model: text
# Optional bearer token for cloud-hosted endpoints. Empty
# string means no Authorization header is sent.
api_key: text
# Optional system prompt. Empty string omits the system
# message and lets the model use its built-in default.
system_prompt: text
# Outputs produced.
outputs:
# The assistant's plain-text reply.
response: text
# The endpoint the response was generated against. Used for
# audit correlation.
model_endpoint: text
# The model identifier as supplied to the LLM API.
model_name: text
# SHA-256 digest of the served Ollama model, when reachable.
# Empty for non-Ollama endpoints (OpenAI / Anthropic do not
# expose a digest API). Together with model_endpoint and
# model_name this answers the audit question "which exact
# model produced this response?"
model_digest: text
# Permissions required.
#
# The module makes outbound HTTP to the configured endpoint.
# Default declarations cover loopback (Ollama) and the common
# cloud providers. Operators with different endpoints fork
# module.yaml in Phase 0.5; operator-config-driven permission
# overrides arrive in Phase 1+.
permissions:
- "net: localhost"
- "net: 127.0.0.1"
- "net: api.openai.com"
- "net: api.anthropic.com"

5
rust-toolchain.toml Normal file
View file

@ -0,0 +1,5 @@
[toolchain]
channel = "1.86"
targets = ["wasm32-wasip2"]
profile = "minimal"
components = ["rustfmt", "clippy"]

113
src/lib.rs Normal file
View file

@ -0,0 +1,113 @@
//! `llm.chat` — generic Ollama-compatible LLM chat adapter.
//!
//! Sends a single user prompt (with optional system prompt) to an
//! Ollama `/api/chat` endpoint and returns the assistant text.
//! Reports `model_endpoint`, `model_name`, and `model_digest` as
//! separate outputs for audit consumers.
//!
//! v0.1.0 targets Ollama only. OpenAI / Anthropic adapters land
//! when a flow needs them.
mod llm;
use fai_module_sdk::prelude::*;
#[fai_module]
pub fn invoke(_ctx: Context, inputs: Inputs) -> Result<Outputs, ModuleError> {
let prompt = inputs.require_text("prompt")?.to_string();
let endpoint = inputs.require_text("endpoint")?.to_string();
let model = inputs.require_text("model")?.to_string();
let api_key = inputs
.get("api_key")
.and_then(payload_text)
.unwrap_or_default();
let system_prompt = inputs
.get("system_prompt")
.and_then(payload_text)
.unwrap_or_default();
let client = make_client();
let params = crate::llm::ChatParams {
endpoint: &endpoint,
model: &model,
api_key: &api_key,
system_prompt: &system_prompt,
prompt: &prompt,
};
let result = crate::llm::chat_with_identity(&client, &params)
.map_err(|e| ModuleError::internal(e.to_string()))?;
Ok(Outputs::new()
.with_text("response", result.response)
.with_text("model_endpoint", endpoint)
.with_text("model_name", model)
.with_text("model_digest", result.model_digest.unwrap_or_default()))
}
fn payload_text(p: &Payload) -> Option<String> {
match p {
Payload::Text(s) => Some(s.clone()),
_ => None,
}
}
#[cfg(target_arch = "wasm32")]
fn make_client() -> WakiClient {
WakiClient
}
#[cfg(not(target_arch = "wasm32"))]
fn make_client() -> HostStubClient {
HostStubClient
}
#[cfg(not(target_arch = "wasm32"))]
struct HostStubClient;
#[cfg(not(target_arch = "wasm32"))]
#[allow(dead_code)]
impl crate::llm::LlmClient for HostStubClient {
fn post_json(
&self,
_url: &str,
_body: &str,
_api_key: &str,
) -> Result<String, crate::llm::LlmError> {
Err(crate::llm::LlmError::Http(
"LLM HTTP path is unavailable on the host build; only wasm32 supports outbound HTTP"
.to_string(),
))
}
}
#[cfg(target_arch = "wasm32")]
struct WakiClient;
#[cfg(target_arch = "wasm32")]
impl crate::llm::LlmClient for WakiClient {
fn post_json(
&self,
url: &str,
body: &str,
api_key: &str,
) -> Result<String, crate::llm::LlmError> {
let mut request = waki::Client::new()
.post(url)
.header("Content-Type", "application/json")
.body(body.to_string());
if !api_key.is_empty() {
request = request.header("Authorization", &format!("Bearer {api_key}"));
}
let response = request
.send()
.map_err(|e| crate::llm::LlmError::Http(e.to_string()))?;
let status = response.status_code();
if !(200..300).contains(&status) {
return Err(crate::llm::LlmError::Status(status));
}
let bytes = response
.body()
.map_err(|e| crate::llm::LlmError::Http(e.to_string()))?;
String::from_utf8(bytes).map_err(|e| crate::llm::LlmError::Decode(e.to_string()))
}
}

323
src/llm.rs Normal file
View file

@ -0,0 +1,323 @@
//! Ollama-shaped chat client.
//!
//! v0.1.0 targets the Ollama `/api/chat` endpoint. OpenAI- and
//! Anthropic-compatible adapters are deliberately deferred — each
//! has its own request/response shape that warrants its own crate
//! (or at least its own module here) once a flow needs it.
//!
//! All HTTP I/O lives behind a `LlmClient` trait so unit tests can
//! exercise prompt building, response parsing, and the digest
//! probe on the host without making real network calls.
use serde::Serialize;
#[allow(dead_code)]
#[derive(Debug, thiserror::Error)]
pub enum LlmError {
#[error("missing required input '{0}'")]
MissingInput(&'static str),
#[error("http error: {0}")]
Http(String),
#[error("non-success status: {0}")]
Status(u16),
#[error("response body could not be parsed as Ollama schema: {0}")]
Decode(String),
}
pub trait LlmClient {
fn post_json(&self, url: &str, body: &str, api_key: &str) -> Result<String, LlmError>;
}
#[derive(Debug, Clone)]
pub struct ChatParams<'a> {
pub endpoint: &'a str,
pub model: &'a str,
pub api_key: &'a str,
pub system_prompt: &'a str,
pub prompt: &'a str,
}
#[derive(Serialize)]
struct OllamaMessage<'a> {
role: &'a str,
content: &'a str,
}
#[derive(Serialize)]
struct OllamaRequest<'a> {
model: &'a str,
messages: Vec<OllamaMessage<'a>>,
stream: bool,
}
/// Build the request body for an Ollama `/api/chat` invocation.
/// The system prompt is omitted from the messages list when empty
/// so a deployment can use the model's built-in system prompt.
pub fn build_ollama_body(p: &ChatParams) -> String {
let mut messages = Vec::with_capacity(2);
if !p.system_prompt.is_empty() {
messages.push(OllamaMessage {
role: "system",
content: p.system_prompt,
});
}
messages.push(OllamaMessage {
role: "user",
content: p.prompt,
});
let req = OllamaRequest {
model: p.model,
messages,
stream: false,
};
serde_json::to_string(&req).unwrap_or_else(|_| String::from("{}"))
}
/// Extract the assistant's message text from an Ollama
/// /api/chat response.
pub fn extract_ollama_content(body: &str) -> Result<String, LlmError> {
let v: serde_json::Value =
serde_json::from_str(body).map_err(|e| LlmError::Decode(e.to_string()))?;
v.get("message")
.and_then(|m| m.get("content"))
.and_then(|c| c.as_str())
.map(|s| s.to_string())
.ok_or_else(|| LlmError::Decode("missing message.content".into()))
}
#[derive(Debug, Clone)]
pub struct ChatWithIdentity {
pub response: String,
pub model_digest: Option<String>,
}
/// Run an Ollama chat call AND probe the model digest. Probe is
/// best-effort — non-Ollama endpoints (no `/api/chat` suffix) and
/// transient failures yield `model_digest = None` rather than
/// failing the whole call.
pub fn chat_with_identity<C: LlmClient>(
client: &C,
p: &ChatParams,
) -> Result<ChatWithIdentity, LlmError> {
if p.endpoint.is_empty() {
return Err(LlmError::MissingInput("endpoint"));
}
if p.model.is_empty() {
return Err(LlmError::MissingInput("model"));
}
if p.prompt.is_empty() {
return Err(LlmError::MissingInput("prompt"));
}
let body = build_ollama_body(p);
let response_body = client.post_json(p.endpoint, &body, p.api_key)?;
let response = extract_ollama_content(&response_body)?;
let model_digest = probe_model_digest(client, p);
Ok(ChatWithIdentity {
response,
model_digest,
})
}
fn probe_model_digest<C: LlmClient>(client: &C, p: &ChatParams) -> Option<String> {
let show_url = derive_show_url(p.endpoint)?;
let body = serde_json::to_string(&serde_json::json!({ "name": p.model })).ok()?;
let response = client.post_json(&show_url, &body, p.api_key).ok()?;
extract_show_digest(&response)
}
pub fn derive_show_url(chat_endpoint: &str) -> Option<String> {
if chat_endpoint.ends_with("/api/chat") {
let head_len = chat_endpoint.len() - "/api/chat".len();
let mut url = String::with_capacity(head_len + "/api/show".len());
url.push_str(&chat_endpoint[..head_len]);
url.push_str("/api/show");
Some(url)
} else {
None
}
}
pub fn extract_show_digest(body: &str) -> Option<String> {
let v: serde_json::Value = serde_json::from_str(body).ok()?;
let candidates = [
v.get("digest"),
v.get("details").and_then(|d| d.get("digest")),
v.get("model_info").and_then(|d| d.get("digest")),
];
for cand in candidates {
if let Some(s) = cand.and_then(|v| v.as_str()) {
if !s.is_empty() {
return Some(s.to_string());
}
}
}
None
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use std::cell::RefCell;
struct MockClient {
responses: RefCell<Vec<Result<String, LlmError>>>,
}
impl MockClient {
fn new(responses: Vec<Result<String, LlmError>>) -> Self {
Self {
responses: RefCell::new(responses),
}
}
}
impl LlmClient for MockClient {
fn post_json(&self, _url: &str, _body: &str, _api_key: &str) -> Result<String, LlmError> {
self.responses
.borrow_mut()
.pop()
.unwrap_or(Err(LlmError::Http("no more mock responses".into())))
}
}
#[test]
fn ollama_body_includes_system_when_provided() {
let p = ChatParams {
endpoint: "http://x/api/chat",
model: "qwen",
api_key: "",
system_prompt: "be helpful",
prompt: "hello",
};
let body = build_ollama_body(&p);
let v: serde_json::Value = serde_json::from_str(&body).unwrap();
let messages = v["messages"].as_array().unwrap();
assert_eq!(messages.len(), 2);
assert_eq!(messages[0]["role"], "system");
assert_eq!(messages[0]["content"], "be helpful");
assert_eq!(messages[1]["role"], "user");
assert_eq!(messages[1]["content"], "hello");
}
#[test]
fn ollama_body_omits_system_when_empty() {
let p = ChatParams {
endpoint: "http://x/api/chat",
model: "qwen",
api_key: "",
system_prompt: "",
prompt: "hello",
};
let body = build_ollama_body(&p);
let v: serde_json::Value = serde_json::from_str(&body).unwrap();
let messages = v["messages"].as_array().unwrap();
assert_eq!(messages.len(), 1);
assert_eq!(messages[0]["role"], "user");
}
#[test]
fn extract_content_pulls_message_content() {
let body = r#"{"message":{"role":"assistant","content":"hi there"},"done":true}"#;
assert_eq!(extract_ollama_content(body).unwrap(), "hi there");
}
#[test]
fn extract_content_errors_on_missing_field() {
let body = r#"{"done":true}"#;
assert!(matches!(
extract_ollama_content(body),
Err(LlmError::Decode(_))
));
}
#[test]
fn derive_show_url_swaps_chat_suffix() {
assert_eq!(
derive_show_url("http://localhost:11434/api/chat").as_deref(),
Some("http://localhost:11434/api/show")
);
}
#[test]
fn derive_show_url_returns_none_for_non_ollama() {
assert!(derive_show_url("https://api.openai.com/v1/chat/completions").is_none());
}
#[test]
fn extract_show_digest_finds_top_level() {
let body = r#"{"digest":"sha256:abc"}"#;
assert_eq!(extract_show_digest(body).as_deref(), Some("sha256:abc"));
}
#[test]
fn extract_show_digest_falls_back_to_nested() {
let body = r#"{"details":{"digest":"sha256:nested"}}"#;
assert_eq!(extract_show_digest(body).as_deref(), Some("sha256:nested"));
}
#[test]
fn chat_with_identity_records_digest_when_show_responds() {
let canned_chat = r#"{"message":{"content":"the response"},"done":true}"#.to_string();
let canned_show = r#"{"digest":"sha256:deadbeef"}"#.to_string();
let client = MockClient::new(vec![Ok(canned_show), Ok(canned_chat)]);
let p = ChatParams {
endpoint: "http://localhost:11434/api/chat",
model: "qwen",
api_key: "",
system_prompt: "",
prompt: "hi",
};
let result = chat_with_identity(&client, &p).unwrap();
assert_eq!(result.response, "the response");
assert_eq!(result.model_digest.as_deref(), Some("sha256:deadbeef"));
}
#[test]
fn chat_with_identity_swallows_show_failure() {
let canned_chat = r#"{"message":{"content":"ok"}}"#.to_string();
let client = MockClient::new(vec![Err(LlmError::Status(500)), Ok(canned_chat)]);
let p = ChatParams {
endpoint: "http://localhost:11434/api/chat",
model: "qwen",
api_key: "",
system_prompt: "",
prompt: "hi",
};
let result = chat_with_identity(&client, &p).unwrap();
assert_eq!(result.response, "ok");
assert_eq!(result.model_digest, None);
}
#[test]
fn chat_with_identity_skips_probe_for_non_ollama() {
let canned_chat = r#"{"message":{"content":"ok"}}"#.to_string();
let client = MockClient::new(vec![Ok(canned_chat)]);
let p = ChatParams {
endpoint: "https://api.openai.com/v1/chat/completions",
model: "gpt",
api_key: "k",
system_prompt: "",
prompt: "hi",
};
let result = chat_with_identity(&client, &p).unwrap();
assert_eq!(result.response, "ok");
assert_eq!(result.model_digest, None);
}
#[test]
fn empty_prompt_is_rejected() {
let client = MockClient::new(vec![]);
let p = ChatParams {
endpoint: "http://x/api/chat",
model: "x",
api_key: "",
system_prompt: "",
prompt: "",
};
assert!(matches!(
chat_with_identity(&client, &p),
Err(LlmError::MissingInput("prompt"))
));
}
}