This commit is contained in:
Tristan D. 2024-07-21 02:42:48 +02:00
commit fdf7cccacf
Signed by: tristan
SSH key fingerprint: SHA256:3RU4RLOoM8oAjFU19f1W6t8uouZbA7GWkaSW6rjp1k8
80 changed files with 15076 additions and 0 deletions

4
.envrc Normal file
View file

@ -0,0 +1,4 @@
if ! has nix_direnv_version || ! nix_direnv_version 2.3.0; then
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/2.3.0/direnvrc" "sha256-Dmd+j63L84wuzgyjITIfSxSD57Tx7v51DMxVZOsiUD8="
fi
use flake

30
.gitignore vendored Normal file
View file

@ -0,0 +1,30 @@
# Generated by Cargo
# will have compiled files and executables
/target/
pkg
# These are backup files generated by rustfmt
**/*.rs.bk
# node e2e test tools and outputs
node_modules
node_modules/
test-results/
end2end/playwright-report/
playwright/.cache/
.direnv
# App artifacts
db.sqlite3*
public/*-result.csv
# logs
*.log
.ape-*
.llamafile/
llamafile.git
.direnv/
/.direnv/

34
.nix/cargo-leptos.nix Normal file
View file

@ -0,0 +1,34 @@
{
fetchFromGitHub,
lib,
pkg-config,
rustPlatform,
stdenv,
}: let
inherit (lib) optionals;
in
rustPlatform.buildRustPackage rec {
pname = "cargo-leptos";
version = "0.2.16";
src = fetchFromGitHub {
owner = "leptos-rs";
repo = pname;
rev = "v0.2.16";
hash = "sha256-yDBVo3GarKvcuMX7mxdxx0SJSJ5VOX3bUx6XmYxLfq4=";
};
cargoHash = "sha256-DZbZ3SHGWvje0gEqlx2mdLvCR4U3Xzkp8gS9FIbxW6g=";
# https://github.com/leptos-rs/cargo-leptos#dependencies
buildFeatures = ["no_downloads"]; # cargo-leptos will try to install missing dependencies on its own otherwise
doCheck = false; # Check phase tries to query crates.io
meta = with lib; {
description = "A build tool for the Leptos web framework";
homepage = "https://github.com/leptos-rs/cargo-leptos";
changelog = "https://github.com/leptos-rs/cargo-leptos/releases/tag/${version}";
license = with licenses; [mit];
maintainers = with maintainers; [benwis];
};
}

66
Cargo.toml Normal file
View file

@ -0,0 +1,66 @@
[profile.dev]
opt-level = 1
lto = "thin"
[profile.dev.package."*"]
opt-level = 3
[profile.dev.package.camt_to_csv_ui]
opt-level = 1
[profile.dev.package.eth_web_ui]
opt-level = 1
[profile.dev.package.cbg_forms]
opt-level = 1
[profile.release]
opt-level = 3
codegen-units = 1
lto = "fat"
strip = "debuginfo"
# Defines a size-optimized profile for the WASM bundle in release mode
[profile.wasm-release]
inherits = "release"
opt-level = 'z'
codegen-units = 1
lto = "fat"
panic = "abort"
[workspace]
members = ["camt_to_csv_ui", "cbg_forms", "eth_web_ui", "vewa_xls_export"]
resolver = "2"
[workspace.package]
authors = ["Tristan Druyen"]
description = "The Ökonzept monorepo"
license = "AGPL-3.0-or-later"
publish = false
readme = "README.md"
repository = "https://git.vlt81.de/oekonzept/oeko-mono"
version = "0.1.1"
[workspace.dependencies]
leptos = { version = "0.6", features = ["serde"] }
leptos_axum = { version = "0.6" }
leptos_meta = { version = "0.6" }
leptos_router = { version = "0.6" }
server_fn = { version = "0.6" }
axum = { version = "0.7", features = ["macros"] }
http = "1.1"
wasm-bindgen = "=0.2.92"
[workspace.metadata.cargo-all-features]
skip_feature_sets = [["csr", "ssr"], ["csr", "hydrate"], ["ssr", "hydrate"]]
# [[workspace.metadata.leptos]]
# name = "oeko-mono"
# output-name = "oeko-mono"
# site-root = "target/site"
# assets-dir = "public"
# site-pkg-dir = "pkg"
# style-file = "style/main.sass"
# site-addr = "127.0.0.1:3000"
# bin-package = "server"
# bin-target-triple = "x86_64-unknown-linux-gnu"
# lib-package = "wasm-lib"
# tailwind-input-file = "style/tailwind.css"
# tailwind-config-file = "./tailwind.config.js" # TODO How to change this for embed ??

11
README.md Normal file
View file

@ -0,0 +1,11 @@
# Redvau.lt AI Monorepo
## TODOS
- nix
- readd new llama.cpp with automated patches
- add build override for rocmTarget etc
- agent
- add experimental rag+agent framework

182
flake.lock generated Normal file
View file

@ -0,0 +1,182 @@
{
"nodes": {
"devshell": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
},
"locked": {
"lastModified": 1717408969,
"narHash": "sha256-Q0OEFqe35fZbbRPPRdrjTUUChKVhhWXz3T9ZSKmaoVY=",
"owner": "numtide",
"repo": "devshell",
"rev": "1ebbe68d57457c8cae98145410b164b5477761f4",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "devshell",
"type": "github"
}
},
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1701680307,
"narHash": "sha256-kAuep2h5ajznlPMD9rnQyffWG8EM/C73lejGofXvdM8=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "4022d587cbbfd70fe950c1e2083a02621806a725",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_2": {
"inputs": {
"systems": "systems_2"
},
"locked": {
"lastModified": 1710146030,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1704161960,
"narHash": "sha256-QGua89Pmq+FBAro8NriTuoO/wNaUtugt29/qqA8zeeM=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "63143ac2c9186be6d9da6035fa22620018c85932",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1721116560,
"narHash": "sha256-++TYlGMAJM1Q+0nMVaWBSEvEUjRs7ZGiNQOpqbQApCU=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "9355fa86e6f27422963132c2c9aeedb0fb963d93",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_3": {
"locked": {
"lastModified": 1718428119,
"narHash": "sha256-WdWDpNaq6u1IPtxtYHHWpl5BmabtpmLnMAx0RdJ/vo8=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "e6cea36f83499eb4e9cd184c8a8e823296b50ad5",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"npmlock2nix": {
"flake": false,
"locked": {
"lastModified": 1673447413,
"narHash": "sha256-sJM82Sj8yfQYs9axEmGZ9Evzdv/kDcI9sddqJ45frrU=",
"owner": "nix-community",
"repo": "npmlock2nix",
"rev": "9197bbf397d76059a76310523d45df10d2e4ca81",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "npmlock2nix",
"type": "github"
}
},
"root": {
"inputs": {
"devshell": "devshell",
"flake-utils": "flake-utils_2",
"nixpkgs": "nixpkgs_2",
"npmlock2nix": "npmlock2nix",
"rust-overlay": "rust-overlay"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": "nixpkgs_3"
},
"locked": {
"lastModified": 1721182796,
"narHash": "sha256-n6w4IhmVeRU+32vH93+8nqZtEZ0Zcy31Hg1GpH1g4Rk=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "d064703dc0657a49a17671c74b1a15ea7433e753",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"systems_2": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

120
flake.nix Normal file
View file

@ -0,0 +1,120 @@
{
description = "A Nix-flake-based Rust development environment";
nixConfig = {
extra-substituters = [ "https://nixcache.vlt81.de" ];
extra-trusted-public-keys = [ "nixcache.vlt81.de:nw0FfUpePtL6P3IMNT9X6oln0Wg9REZINtkkI9SisqQ=" ];
};
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
rust-overlay.url = "github:oxalica/rust-overlay";
flake-utils.url = "github:numtide/flake-utils";
devshell.url = "github:numtide/devshell";
npmlock2nix = {
url = "github:nix-community/npmlock2nix";
flake = false;
};
};
outputs =
{ self
, nixpkgs
, rust-overlay
, flake-utils
, devshell
, npmlock2nix
,
}:
flake-utils.lib.eachDefaultSystem
(system:
let
overlays = [
rust-overlay.overlays.default
devshell.overlays.default
(final: prev: {
customRustToolchain = prev.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
})
(final: prev: {
npmlock2nix = import npmlock2nix { pkgs = prev; };
})
];
pkgs = import nixpkgs {
inherit system overlays;
};
customNodeModules = pkgs.npmlock2nix.v2.node_modules {
src = ./.;
nodejs = pkgs.nodejs_20;
};
buildInputs = with pkgs; [
harfbuzz
openssl
pango
sqlite
mariadb
zlib
clang
libclang
gzip
coreutils
glib
glibc
];
in
{
apps.devshell = self.outputs.devShells.${system}.default.flakeApp;
packages = {
cargo-leptos = pkgs.callPackage ./.nix/cargo-leptos.nix { };
};
devShells.default = pkgs.mkShell {
packages = with pkgs;
[
customNodeModules
customRustToolchain
binaryen
cacert
cargo-bloat
cargo-docset
cargo-machete
cargo-limit
cargo-deny
cargo-edit
cargo-watch
cargo-make
cargo-udeps
self.packages.${system}.cargo-leptos
(wasm-bindgen-cli.override {
version = "0.2.92";
hash = "sha256-1VwY8vQy7soKEgbki4LD+v259751kKxSxmo/gqE6yV0=";
cargoHash = "sha256-aACJ+lYNEU8FFBs158G1/JG8sc6Rq080PeKCMnwdpH0=";
})
cargo-outdated
cargo-release
calc
jre8 # needed for xmlls
dart-sass
fish
inotify-tools
leptosfmt
mold
nodejs_20
pkg-config
rustywind
sccache
sqlx-cli
unzip
]
++ buildInputs;
buildInputs = buildInputs;
shellHook = ''
# setup node-modules
export NPM_LOCAL_PREFIX=${customNodeModules}/node_modules
(ln -s $NPM_LOCAL_PREFIX ./node_modules 2>/dev/null || unlink ./node_modules) && ln -s $NPM_LOCAL_PREFIX ./node_modules 2>/dev/null
# export NIX_LD_LIBRARY_PATH=${pkgs.lib.makeLibraryPath buildInputs}:$NIX_LD_LIBRARY_PATH
export LEPTOS_SASS_VERSION=1.71.0
export LEPTOS_TAILWIND_VERSION=3.4.1
export MALLOC_CONF=thp:always,metadata_thp:always
'';
};
});
}

View file

@ -0,0 +1,10 @@
[unstable]
codegen-backend = true
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "link-arg=-fuse-ld=mold"]
linker = "clang"
codegen-backend = { dev = "cranelift" }
[profile.server-dev]
codegen-backend = "cranelift"

View file

@ -0,0 +1,2 @@
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "target-feature=+crt-static"]

15
llama_forge_rs/.dist/watch.fish Executable file
View file

@ -0,0 +1,15 @@
#!/usr/bin/env fish
echo "watchPWD: $(pwd)"
set DIRECTORY_TO_WATCH "./src"
set SCRIPT_TO_RUN "echo a && leptosfmt $(pwd) && rustywind --write ./src && echo b"
while true
# Wait for any change in the directory
inotifywait -r -e modify,create,delete,move $DIRECTORY_TO_WATCH
# Run your script
bash -c "$SCRIPT_TO_RUN"
sleep 5
end

View file

@ -0,0 +1,4 @@
.git/
target/
Dockerfile
docker-compose.yml

4
llama_forge_rs/.envrc Normal file
View file

@ -0,0 +1,4 @@
if ! has nix_direnv_version || ! nix_direnv_version 2.3.0; then
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/2.3.0/direnvrc" "sha256-Dmd+j63L84wuzgyjITIfSxSD57Tx7v51DMxVZOsiUD8="
fi
use flake

View file

@ -0,0 +1,75 @@
name: Cargo testing
on:
workflow_dispatch:
push:
tags:
- "v[0-9]+.[0-9]+.[0-9]+"
branches:
- 'main'
pull_request:
branches:
- 'main'
jobs:
check:
runs-on: ubuntu-latest
strategy:
max-parallel: 1
matrix:
build_type: ['release', 'debug']
concurrency:
group: ci-cargo-check-${{ github.ref }}-${{ matrix.build_type }}
cancel-in-progress: true
steps:
- name: Checkout
uses: actions/checkout@1d96c772d19495a3b5c517cd2bc0cb401ea0529f # v4
- name: Install toolchain
uses: https://github.com/actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1
with:
profile: default
toolchain: nightly-2024-03-23
components: cargo, rustfmt, clippy
override: true
- name: Add wasm32-unknown-unknown
run: rustup target add wasm32-unknown-unknown
- name: Set env
run: echo "CARGO_BUILD_JOBS=2" >> $GITHUB_ENV
- name: Run cargo check
run: |
if [[ "${{ matrix.build_type }}" == 'release' ]]; then
cargo check --all-features --release
else
cargo check --all-features
fi
test:
runs-on: ubuntu-latest
strategy:
max-parallel: 1
matrix:
build_type: ['release', 'debug']
concurrency:
group: ci-cargo-test-${{ github.ref }}-${{ matrix.build_type }}
cancel-in-progress: true
steps:
- name: Checkout
uses: actions/checkout@1d96c772d19495a3b5c517cd2bc0cb401ea0529f # v4
- name: Install toolchain
uses: https://github.com/actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1
with:
profile: default
toolchain: nightly-2024-03-23
components: cargo, rustfmt, clippy
override: true
- name: Add wasm32-unknown-unknown
run: rustup target add wasm32-unknown-unknown
- name: Set env
run: echo "CARGO_BUILD_JOBS=2" >> $GITHUB_ENV
- name: Run cargo test
run: |
if [[ "${{ matrix.build_type }}" == 'release' ]]; then
cargo test --all-features --release
else
cargo test --all-features
fi

View file

@ -0,0 +1,25 @@
name: Forgejo Actions Demo
run-name: ${{ forgejo.actor }} is testing out Forgejo Actions 🚀
on: [push]
jobs:
Explore-Forgejo-Actions:
runs-on: ubuntu-latest
steps:
- run: echo "🎉 The job was automatically triggered by a ${{ gitea.event_name }} event."
- run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by Forgejo!"
- run: echo "🔎 The name of your branch is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}."
- name: Check out repository code
uses: actions/checkout@1d96c772d19495a3b5c517cd2bc0cb401ea0529f # v4
- run: echo "💡 The ${{ gitea.repository }} repository has been cloned to the runner."
- run: echo "🖥️ The workflow is now ready to test your code on the runner."
- name: List files in the repository
run: |
ls ${{ gitea.workspace }}
- name: List files
run: |
ls
- name: Echo pwd
run: |
pwd
- run: echo "🍏 This job's status is ${{ job.status }}."

View file

@ -0,0 +1,58 @@
name: Publish Docker
on:
workflow_dispatch:
push:
tags:
- "v[0-9]+.[0-9]+.[0-9]+"
jobs:
build_and_push:
runs-on: ubuntu-latest
strategy:
max-parallel: 1
matrix:
build_type: ['release', 'debug']
concurrency:
group: ci-${{ github.ref }}-${{ matrix.build_type }}
cancel-in-progress: true
steps:
- name: Set tag
run: |
if [[ -n "${{ inputs.tag }}" ]]; then
TAG=${{ inputs.tag }}
elif [[ "${{ github.ref_name }}" == 'main' ]]; then
TAG="latest"
else
TAG=${{ github.ref_name }}
fi
echo "TAG=${TAG}" >> $GITHUB_ENV
echo "BUILD_PKG=llama_forge_rs" >> $GITHUB_ENV
echo "BUILD_TYPE=${{ matrix.build_type }}" >> $GITHUB_ENV
echo "IMAGE=${{matrix.build_pkg}}:${TAG}-${{matrix.build_type}}" >> $GITHUB_ENV
echo "TAG=${TAG}"
echo "BUILD_PKG=llama_forge_rs"
echo "BUILD_TYPE=${{ matrix.build_type }}"
echo "IMAGE=${{matrix.build_pkg}}:${TAG}-${{matrix.build_type}}"
- name: Checkout
uses: actions/checkout@1d96c772d19495a3b5c517cd2bc0cb401ea0529f # v4
- name: Install docker
uses: https://github.com/papodaca/install-docker-action@main
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@d70bba72b1f3fd22344832f00baa16ece964efeb # v3
- name: Login to DockerHub
uses: docker/login-action@e92390c5fb421da1463c202d546fed0ec5c39f20 # v3
with:
registry: git.vlt81.de
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Build and push
uses: docker/build-push-action@2cdde995de11925a030ce8070c3d77a52ffcf1c0 # v5
with:
context: .
platforms: linux/amd64
push: true
tags: git.vlt81.de/oekonzept/${{env.IMAGE}}
build-args: |
BUILD_TYPE=${{env.BUILD_TYPE}}
BUILD_PKG=${{env.BUILD_PKG}}

28
llama_forge_rs/.gitignore vendored Normal file
View file

@ -0,0 +1,28 @@
# Generated by Cargo
# will have compiled files and executables
/target/
pkg
# These are backup files generated by rustfmt
**/*.rs.bk
# node e2e test tools and outputs
node_modules
node_modules/
test-results/
end2end/playwright-report/
playwright/.cache/
.direnv
# App artifacts
db.sqlite3*
public/*-result.csv
# logs
*.log
.ape-*
.llamafile/
llamafile.git

View file

@ -0,0 +1,34 @@
{
fetchFromGitHub,
lib,
pkg-config,
rustPlatform,
stdenv,
}: let
inherit (lib) optionals;
in
rustPlatform.buildRustPackage rec {
pname = "cargo-leptos";
version = "0.2.16";
src = fetchFromGitHub {
owner = "leptos-rs";
repo = pname;
rev = "v0.2.16";
hash = "sha256-yDBVo3GarKvcuMX7mxdxx0SJSJ5VOX3bUx6XmYxLfq4=";
};
cargoHash = "sha256-DZbZ3SHGWvje0gEqlx2mdLvCR4U3Xzkp8gS9FIbxW6g=";
# https://github.com/leptos-rs/cargo-leptos#dependencies
buildFeatures = ["no_downloads"]; # cargo-leptos will try to install missing dependencies on its own otherwise
doCheck = false; # Check phase tries to query crates.io
meta = with lib; {
description = "A build tool for the Leptos web framework";
homepage = "https://github.com/leptos-rs/cargo-leptos";
changelog = "https://github.com/leptos-rs/cargo-leptos/releases/tag/${version}";
license = with licenses; [mit];
maintainers = with maintainers; [benwis];
};
}

View file

@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "UPDATE backend_process\n SET status == ?\n WHERE id == ?",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "2a4e3b46a4cc97a464a5f6f7ada1f97035901ae28f7affb59f986ed1c326ec90"
}

View file

@ -0,0 +1,38 @@
{
"db_name": "SQLite",
"query": "SELECT version, model_dir, default_model, created_at FROM settings ORDER BY version DESC LIMIT 1",
"describe": {
"columns": [
{
"name": "version",
"ordinal": 0,
"type_info": "Int64"
},
{
"name": "model_dir",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "default_model",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "created_at",
"ordinal": 3,
"type_info": "Datetime"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false,
false,
false
]
},
"hash": "3cf9271b73aa2f27f6d92c05d15fc4a59f7bc7a57573ea459f8cd566b56c61f8"
}

View file

@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "UPDATE backend_process SET status = 'waiting_for_stop' WHERE status != 'finished'",
"describe": {
"columns": [],
"parameters": {
"Right": 0
},
"nullable": []
},
"hash": "669b50cacde18cc979c2726efdda45fc58c56b122f0939f6ad941fe8e9094002"
}

View file

@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO backend_process (settings_version, status) VALUES (?, 'waiting_for_start')",
"describe": {
"columns": [],
"parameters": {
"Right": 1
},
"nullable": []
},
"hash": "69960848ad600a9408df78092bea6d4005b51d51fb43c348998b25dd0ea20c7e"
}

View file

@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT version FROM settings ORDER BY version DESC LIMIT 1",
"describe": {
"columns": [
{
"name": "version",
"ordinal": 0,
"type_info": "Int64"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false
]
},
"hash": "ac9673aec5048b46441f7b8de70ccaa5eb602fea17ed22f8acc54681e856a338"
}

View file

@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "UPDATE backend_process SET status = 'waiting_for_stop'",
"describe": {
"columns": [],
"parameters": {
"Right": 0
},
"nullable": []
},
"hash": "bbb33dad0c994542680852f2f943f2ed7b4c215c0dd3bb5dedf11a12e41e6e99"
}

View file

@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "SELECT status FROM backend_process ORDER BY id DESC LIMIT 1",
"describe": {
"columns": [
{
"name": "status",
"ordinal": 0,
"type_info": "Text"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false
]
},
"hash": "ddd0377a08bd052c2d2a235a9858bee28fd3115dd1c4063219e9a9e83a564681"
}

View file

@ -0,0 +1,12 @@
{
"db_name": "SQLite",
"query": "INSERT INTO settings (model_dir, default_model) VALUES (?, ?)",
"describe": {
"columns": [],
"parameters": {
"Right": 2
},
"nullable": []
},
"hash": "e4c94a6f9413870a1a8d322cbbf7514a3cbe727d26616a10917899fc1059e4fe"
}

6319
llama_forge_rs/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

219
llama_forge_rs/Cargo.toml Normal file
View file

@ -0,0 +1,219 @@
[package]
name = "llama_forge_rs"
edition = "2021"
authors = ["Tristan Druyen"]
description = "The LLama Forge RS"
license = "AGPL-3.0-or-later"
publish = false
readme = "README.md"
repository = "https://git.vlt81.de/vault81/llama_forge_rs"
version = "0.1.0"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
wasm-bindgen = "=0.2.92"
leptos = { version = "0.6", features = [
"serde",
"nightly",
"experimental-islands",
] }
leptos_axum = { version = "0.6", optional = true }
leptos_meta = { version = "0.6", features = ["nightly"] }
leptos_router = { version = "0.6", features = ["nightly"] }
server_fn = { version = "0.6", features = ["rkyv", "multipart"] }
axum = { version = "0.7", features = ["macros"], optional = true }
tokio = { version = "1.37.0", features = ["full"], optional = true }
tower = { version = "0.4", optional = true }
http = "1.1"
tower-http = { version = "0.5", features = [
"compression-full",
"decompression-full",
"fs",
"trace",
], optional = true }
serde = { version = "1.0.198", features = ["unstable", "rc", "derive"] }
serde_json = { version = "1.0.116" }
sqlx = { version = "0.7.4", features = ["chrono", "macros"] }
tracing = { version = "0.1.40" }
tracing-wasm = { version = "0.2.1" }
tracing-subscriber = { version = "0.3.18", features = [
"env-filter",
"tracing",
"serde",
"serde_json",
], optional = true }
anyhow = { version = "1.0.82", features = ["backtrace"] }
cfg-if = "1.0.0"
console_error_panic_hook = "0.1"
once_cell = { version = "1.19.0", optional = true }
thiserror = "1.0.59"
gloo-timers = { version = "0.3.0", features = ["futures"] }
rand = "0.8.5"
web-sys = { version = "0.3.69", features = ["FileList", "File"] }
# camt to csv deps
chrono = { version = "0.4.38", features = ["serde", "rkyv"] }
regex = { version = "1.10.4", features = ["use_std"], optional = true }
futures = { version = "0.3.30" }
async-broadcast = { version = "0.7.0", optional = true }
dashmap = { version = "5.5.3", optional = true, features = ["inline", "serde"] }
pin-project-lite = "0.2.14"
strum = { version = "0.26.2", features = ["derive", "strum_macros"] }
uuid = { version = "1.8.0", features = ["v4", "v7", "js", "serde"] }
gloo-net = "0.5.0"
wasm-bindgen-futures = "0.4.42"
reqwest = { version = "0.12.3", optional = true, features = ["json", "stream"] }
reqwest-eventsource = { version = "0.6.0", optional = true }
futures-util = { version = "0.3.30" }
tokio-stream = { version = "0.1.15", features = ["full"], optional = true }
async-trait = "0.1.80"
bytes = "1.6.0"
tao = { version = "0.27.0", optional = true, features = ["serde"] }
wry = { version = "0.39.0", optional = true, features = ["serde", "tracing"] }
winit = { version = "0.29.15", optional = true, features = ["serde"] }
gtk = { version = "0.18.1", optional = true }
x11-dl = { version = "2.21.0", optional = true }
rust-embed = { version = "8.3.0", optional = true }
mime_guess = { version = "2.0.4", optional = true }
tracing-test = "0.2.4"
sysinfo = { version = "0.30.11", optional = true }
derive_more = { version = "0.99.17", features = ["nightly"] }
sqlx-macros = { version = "0.7.4", optional = true, features = ["chrono", "json", "migrate", "sqlite", "uuid"] }
# TODO Add desktop/gui feature
[features]
default = ["ssr"]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
ssr = [
"dep:async-broadcast",
"dep:axum",
"dep:dashmap",
"dep:leptos_axum",
"dep:gtk",
"dep:once_cell",
"dep:reqwest",
"dep:reqwest-eventsource",
"dep:regex",
"dep:rust-embed",
"dep:mime_guess",
"dep:tao",
"dep:tokio",
"dep:sysinfo",
"dep:tower",
"dep:tokio-stream",
"dep:tower-http",
"dep:tracing-subscriber",
"dep:winit",
"dep:wry",
"dep:x11-dl",
"dep:sqlx-macros",
"sqlx/sqlite",
"sqlx/migrate",
"sqlx/runtime-tokio",
"leptos/ssr",
"leptos_meta/ssr",
"leptos_router/ssr",
]
[profile.dev]
opt-level = 1
lto = "thin"
[profile.dev.package."*"]
opt-level = 3
[profile.dev.package.llama_forge_rs]
opt-level = 1
[profile.release]
opt-level = 3
codegen-units = 1
lto = "fat"
strip = "debuginfo"
# Defines a size-optimized profile for the WASM bundle in release mode
[profile.wasm-release]
inherits = "release"
opt-level = 'z'
codegen-units = 1
lto = "fat"
panic = "abort"
[package.metadata.cargo-all-features]
skip_feature_sets = [["ssr", "hydrate"]]
[package.metadata.leptos]
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
output-name = "llama_forge_rs"
# The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup.
site-root = "target/site"
# The site-root relative folder where all compiled output (JS, WASM and CSS) is written
# Defaults to pkg
site-pkg-dir = "pkg"
# [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to <site-root>/<site-pkg>/app.css
style-file = "style/main.scss"
# separate-front-target-dir = true
tailwind-input-file = "style/tailwind.css"
tailwind-config-file = "./tailwind.config.js"
# Assets source dir. All files found here will be copied and synchronized to site-root.
# The assets-dir cannot have a sub directory with the same name/path as site-pkg-dir.
#
# Optional. Env: LEPTOS_ASSETS_DIR.
assets-dir = "public"
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.
site-addr = "0.0.0.0:3000"
# The port to use for automatic reload monitoring
reload-port = 3001
# [Optional] Command to use when running end2end tests. It will run in the end2end dir.
# [Windows] for non-WSL use "npx.cmd playwright test"
# This binary name can be checked in Powershell with Get-Command npx
end2end-cmd = "npx playwright test"
end2end-dir = "end2end"
# The browserlist query used for optimizing the CSS.
browserquery = "defaults"
# Set by cargo-leptos watch when building with that tool. Controls whether autoreload JS will be included in the head
watch = false
# The environment Leptos will run in, usually either "DEV" or "PROD"
env = "DEV"
####
bin-target-triple = "x86_64-unknown-linux-gnu"
# The features to use when compiling the bin target
#
# Optional. Can be over-ridden with the command line parameter --bin-features
bin-features = ["ssr"]
# If the --no-default-features flag should be used when compiling the bin target
#
# Optional. Defaults to false.
bin-default-features = false
# The features to use when compiling the lib target
#
# Optional. Can be over-ridden with the command line parameter --lib-features
lib-features = ["hydrate"]
# If the --no-default-features flag should be used when compiling the lib target
#
# Optional. Defaults to false.
lib-default-features = false
# The profile to use for the lib target when compiling for release
#
# Optional. Defaults to "release".
lib-profile-release = "wasm-release"

85
llama_forge_rs/Dockerfile Normal file
View file

@ -0,0 +1,85 @@
FROM ghcr.io/rust-lang/rust:nightly-bookworm-slim@sha256:a0f43abebdf4b8d3a6e545115af863c77f35b48a63b63b9d174fdb6bbd31315e as build
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
cmake \
curl \
git \
sqlite3 \
npm \
pkg-config \
clang \
gcc \
libssl-dev \
libatk1.0-dev \
libwebkit2gtk-4.1-dev \
libharfbuzz-dev \
libgtk-3-dev \
libsoup-3.0-dev \
libpango1.0-dev \
libgdk-pixbuf-2.0-dev \
zlib1g-dev \
make \
&& rm -rf /var/lib/apt/lists/*
ENV LANG=C.UTF-8
ENV LANGUAGE=C.UTF-8
ENV LC_ALL=C.UTF-8
# install leptos build helper cli
COPY rust-toolchain.toml .
RUN cargo --version
RUN cargo install -f wasm-bindgen-cli --version 0.2.92
RUN cargo install cargo-leptos --version 0.2.16 --force
ADD ./package.json ./package.json
ADD ./package-lock.json ./package-lock.json
RUN npm i -g sass
RUN npm install
# Build
WORKDIR /build
# install rust toolchain
COPY . .
COPY .cargo/docker-config.toml .cargo/config.toml
ARG BUILD_TYPE
ENV BUILD_TYPE=${BUILD_TYPE:-release}
ENV BUILD_PKG=${BUILD_PKG:-llama_forge_rs}
RUN echo Building $BUILD_TYPE for pkg: $BUILD_PKG
ENV VALID_TYPES="debug release"
RUN if ! echo "${VALID_TYPES}" | grep -wq "${BUILD_TYPE}"; then echo "Invalid BUILD_TYPE value. It should be one of ${VALID_TYPES}." && exit 1; fi
ENV LEPTOS_OUTPUT_NAME=${BUILD_PKG}
ENV LEPTOS_SITE_ADDR="0.0.0.0:3000"
ENV LEPTOS_TAILWIND_VERSION=v3.4.3
ENV LEPTOS_SASS_VERSION=1.71.0
ENV LEPTOS_WASM_OPT_VERSION=version_116
ARG CARGO_BUILD_JOBS
ENV CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4}
RUN if [ "$BUILD_TYPE" = "release" ]; then \
cargo leptos build -p $BUILD_PKG --release; \
elif [ "$BUILD_TYPE" = "debug" ]; then \
cargo leptos build -p $BUILD_PKG; \
else \
echo "Invalid BUILD_TYPE value. It should be either 'release' or 'debug'." && exit 1; \
fi
RUN mkdir -p ./out/target \
&& cp -r ./target/site ./out/target/site \
&& cp -r ./target/x86_64-unknown-linux-gnu/$BUILD_TYPE/$BUILD_PKG ./out/server
RUN chmod +x ./out/server
RUN sqlite3 ./out/db.sqlite3 "VACUUM;"
FROM gcr.io/distroless/base-debian12@sha256:611d30d7f6d9992c37b1e1a212eefdf1f7c671deb56db3707e24eb01da8c4c2a
WORKDIR /app
# ADD ./rules.json ./rules.json this should now be provided as a mount
COPY --from=build /build/out ./
ENTRYPOINT ["./server"]
CMD []

651
llama_forge_rs/LICENSE.md Normal file
View file

@ -0,0 +1,651 @@
GNU Affero General Public License
=================================
_Version 3, 19 November 2007_
_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
## Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: **(1)** assert copyright on the software, and **(2)** offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
## TERMS AND CONDITIONS
### 0. Definitions
“This License” refers to version 3 of the GNU Affero General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this
License. Each licensee is addressed as “you”. “Licensees” and
“recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a “modified version” of the
earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based
on the Program.
To “propagate” a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices”
to the extent that it includes a convenient and prominently visible
feature that **(1)** displays an appropriate copyright notice, and **(2)**
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
### 1. Source Code
The “source code” for a work means the preferred form of the work
for making modifications to it. “Object code” means any non-source
form of a work.
A “Standard Interface” means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other
than the work as a whole, that **(a)** is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and **(b)** serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
“Major Component”, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
### 2. Basic Permissions
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
### 4. Conveying Verbatim Copies
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
### 5. Conveying Modified Source Versions
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
* **a)** The work must carry prominent notices stating that you modified
it, and giving a relevant date.
* **b)** The work must carry prominent notices stating that it is
released under this License and any conditions added under section 7.
This requirement modifies the requirement in section 4 to
“keep intact all notices”.
* **c)** You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
* **d)** If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
“aggregate” if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
### 6. Conveying Non-Source Forms
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
* **a)** Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either **(1)** a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or **(2)** access to copy the
Corresponding Source from a network server at no charge.
* **c)** Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
* **d)** Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A “User Product” is either **(1)** a “consumer product”, which means any
tangible personal property which is normally used for personal, family,
or household purposes, or **(2)** anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, “normally used” refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
“Installation Information” for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
### 7. Additional Terms
“Additional permissions” are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
* **a)** Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or
authors of the material; or
* **e)** Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered “further
restrictions” within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
### 8. Termination
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated **(a)**
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and **(b)** permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
### 9. Acceptance Not Required for Having Copies
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
### 10. Automatic Licensing of Downstream Recipients
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
### 11. Patents
A “contributor” is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, “control” includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To “grant” such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either **(1)** cause the Corresponding Source to be so
available, or **(2)** arrange to deprive yourself of the benefit of the
patent license for this particular work, or **(3)** arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. “Knowingly relying” means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is “discriminatory” if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license **(a)** in connection with copies of the covered work
conveyed by you (or copies made from those copies), or **(b)** primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
### 12. No Surrender of Others' Freedom
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
### 13. Remote Network Interaction; Use with the GNU General Public License
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
### 14. Revised Versions of this License
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License “or any later version” applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
### 15. Disclaimer of Warranty
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
### 16. Limitation of Liability
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
_END OF TERMS AND CONDITIONS_
## How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a “Source” link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a “copyright disclaimer” for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
&lt;<http://www.gnu.org/licenses/>&gt;.

View file

@ -0,0 +1,61 @@
[tasks.refresh-all]
description = "clean the repo and rebuild everything"
dependencies = ["clean", "mksitedir", "all"]
[tasks.mksitedir]
script = "mkdir -p ./target/site"
[tasks.all]
description = "rebuild everything"
dependencies = ["docset", "check", "build", "build-release"]
[tasks.build]
category = "Build"
command = "cargo"
args = ["leptos", "build"]
[tasks.build-release]
category = "Build"
command = "cargo"
args = ["leptos", "build", "--release"]
[tasks.run]
command = "cargo"
args = ["leptos", "serve"]
[tasks.docset]
script = '''
cargo docset --workspace --platform-family llama_forge_rs \
&& cp -r target/docset/llama_forge_rs.docset ~/.local/share/Zeal/Zeal/docsets/
'''
[tasks.watch-test]
command = "cargo"
args = [
"watch",
"--",
"cargo",
"ltest",
"--target-dir",
"target/test",
"--all-features",
]
[tasks.watch-check]
command = "cargo"
args = ["watch", "--", "cargo", "lcheck", "--all-features"]
[tasks.watch-fmt]
command = "fish"
args = ["./.dist/watch.fish"]
[tasks.watch-serve]
command = "cargo"
args = ["leptos", "watch", "--hot-reload"]
[tasks.reset-db]
script = '''
rm db.sqlite3 \
&& touch db.sqlite3 \
&& cargo sqlx migrate run --database-url="sqlite:db.sqlite3"
'''

317
llama_forge_rs/PLAN.org Normal file
View file

@ -0,0 +1,317 @@
#+title: Plan
* TODO for 0.0.1-rc1
- [X] processmanager service
- [X] spawn task on app startup
- [X] loop every second
- [X] start processes
- [X] query waiting processes from db
- [X] start them
- [X] change their status to running
- [X] stop finished processes in db & remove from RAM registry
- [X] query status for currently running processes
- [X] stop those that aren't status=running
- [X] set their status to finished
- [ ] must have tweaks
- pass options to model (ngl , path & model)
- gpu/nogpu
- model dropdown (ls *.gguf based)
- size
- markdown formatting with markdown-rs + set inner html
- show small backend starter widget icon /button on chat page
- test faster refresh
- chat persistence
- Config.toml
- package as appimage
- add model mode
- amd/rocm/cuda
- [ ] ideas to investigate before release
- stdout inspection
- visualize setting generation ? [not really useful once settings are per chat?]
* TODO next steps after 0.0.1-rc1
- markdown formatting
- chat persistence
- backend logs inspector
- multiple chats
- per chat settings/model etc
- configurable ngl
- custom backends via pwd, command & args
- custom backend templates
- prompt templates
- sampling settings
- chat/completion mode?
- transfer planning into issues
* Roadmap
0.1 model selection from dir, switch models
- hardcoded ngl
- llamafile in path or ./llamafile only
- one chat
- simple model selection
- llamafile included templates only
0.2
- hardcoded inbuilt chat templates
- multiple chatrooms
- persist settings
- ngl setting
- persist history
- summaries
- extendended backend settings
- max running? running slots?
- better model selection
- extract GGUF metadata
- model downloader ?
- huggingface /api/models hardcoded to my account as owner
- develop some yalu.toml manifest? ?
- chat templates /completions instead of /chat/completions
* Design for 0.1
- Frontend
- settings page
- model dir
- chat settings drawer
- model selection (from dir */*.gguf?)
- chat template (from hardcoded list)
- start/stop
- Backend
- Settings (1)
- model path
- Chat (1)
- Template
- ModelSettigns
- model
- ngl
- BackendProcess (1)
- status: started -> running -> finished
- created from chat & saves its args
- no update, only create&delete
- RunnerBackend
- keep track which processes are running
- start/stop processes when needed
* TODO for 0.1
- Settings api
- #[server] fn update_settings
- model_dir
- Chat Api
- #[server] fn update_chat
- ChatTemplate (llama3, chatml, phi)
- model path
- ngl
- BackendProcess api
- #[server] fn start_process
- #[server] fn stop_process
- #[server] fn restart_process ?
- BackendRunner worker
- UI stuff
- settings page with model_dir
- drawer on chat
- settings (model_path & ngl)
- start/stop
- Package for private release
* TODO Design for backend runners
** TODO
- implement backendconfig CRUD
- backend tab
- implement starting of a specified backendconfig
- "running" tab ?
- add simple per-start settings
- context & ngl
- add model per-start setting
- needs model settings (ie. download path)
- probably need global app settings somewhere
- better message formatting
- markdown conversion
** Newest Synthesis
- 2 Ressources
- BackendConfig
- includes state needed to start backend
- ie. no runtime options like -ctx -m -ngl etc
- for noparams configs only needed ui is a select dropdown
- (NO PARAMS !!!!)
- shipped llamafile
- llamafile PATH
- llama.cpp server in PATH ?
- (not mvp)
- basic & flexible pwd, cmd, args(prefix)
- templates for default options (can probably just be in the ui code, auto-filling the form ?)
- llama.cpp path prebuilt
- llama.cpp path builder
- no explicit nix support for now!
- BackendProcess
- initialy just start/stop with hardcoded config
- RunTimeConfig
- model
- context etc
** Open Questions
- how to model multiple launched instances ?
- could have different parameters or models loadead
** Synthesis ?
- model backend as ressource
- runner can start stop
- build interactor pattern services ?
** (Maybe) better option runner module seperate as a kind of micro subservice
- only startup fn in main, nothing pub apart from that
- server api code stays like a mostly simple crud app
- start background jobs on startub
- starter/manager
- reads intended backend state from sqlite
- has internal state in struct
- makes internal state agree with db
- starts backends
- stops backends
- etc?
- frontend just reads and writes db via server fns
- other background job for having always up-to-date status for backends ?
- expose status checker via backendapi interface trait
** (Maybe) stupid option
- continue current plan, start on demand via server_fn request
- how to handle only starting a single backend
- some in process registry needed ?
* MVP
** Backends
- start on demand
- simple start/stop
- as background service
- simple status via /health
- Options
- llamafile
- in $PATH
- as executable file next to binary, (enables creating a zip which "just works")
- llama.cpp
- via nix via path to llama.cpp directory
- via path to binary
- Settings
- context
- gpu layers
- keep model hardcoded for now
** Chat Prompt Template
- simple template defs to get from chat format (with role) to bare text prompt
- collect some default templates (chatml/llama3)
- migrate to /completions api
- apply to specific models ?
** Model Selection
- set folder in general settings
- read gguf metadata via gguf crate
- per-model settings (layers? ctx?, vram prediction ?)
** Inference settings (in chat as modal or sth like that)
- set sampler params in chat settings
** Settings hierarchy ?
- per_chat>per_model>per_backend>global
** Setting types ?
- Model loading
- context
- gpu layers
- Sampling
- temperature
- Prompt template
* Settings planning
** Per Backend
*** runner config
- pwd
- cmd
- template for args
- model
- chat template
- infer settings ? ( low prio, should switch to other API, that allows settings these at runtime )
** Per Model
*** offloading layers ?
** per chat
*** inference settings( runtime )
* Settings todo
- start/stop
- start current backend on demand, just start stop on settings page
- disable buttons when backend isn ´t running
- only allow llama-cpp/llamafile launch arguments for now
* Next steps (teaser)
- [x] finish basic chat
- [x] bigger bubbles (use screen, +flex grow?/maybe even grid?)
- [x] edit history + system prompt
- [x] regenerate latest response
# - save history to db (postponed until multichat)
- [ ] backend page
- [ ] infer sampling settings
- [ ] running settings (gpu layer, context size etc)
- [ ] model page
- [ ] set model dir
- [ ] list by simple filename (& size)
- [ ] offline metadata (README frontmatter yaml, filename, (gguf crate))
- [ ] chat settings
- [ ] none for now, single model & settigns et is selected on respective pages
* Next steps (private mvp)
- chatrooms
- settings/model/etc per chatroom, multiple settingss ets
* TODO MVP
- [ ] add test model downloader to nix devshell
- [ ] Backend config via TOML
- just based on llama.cpp /completion for now
- [ ] Basic chat GUI
- basic ui with bubbles
- advanced ui with markdown rendering
- fix incomplete quotes ?
- [ ] Prompt template & parameters via TOML
- [ ] Basic DB stuff
- single room history
- prompt templates via DB
- parameter management via DB (e.g. temperature)
- [ ] Advanced chat UI
- Multiple "Rooms"
- Set prompt & params per room
- [ ] Basic RAG
- select vector db
- qdrant ? chroma ?
* TODO Advanced features
- [ ] Backends
- Backend Runner
- llamafile
- llama.cpp nix (via cmd templates ?)
- Backend API config?
- Backend Downloader/Installer
- [ ] Inference Param Templates
- [ ] Prompt Templates
- [ ] model library
- [ ] model downloader
- [ ] model selector
- model data extractionf from gguf
- [ ] quant selector
- automatic offloading layer selection based on vram
- [ ] auto-quantize
- vocab selection
- quant checkboxes
- extract progress ETA
- imatrix generation
- dataset downloader ? (or just include a default one?)
- [ ] Better RAG
- [ ] add multiple embedding models
- [ ] add reranking
- [ ] Generic graph based prompt pre/postprocessing via UI, like ComfyUI
- [ ] DSL ? Some existing scripting stuff ?
- [ ] Graph just as visualization, with text-based config
- [ ] Fancy Graph UI
* TODO Polish
- [ ] Backend Multi-API compat e.g. llama.cpp /completion & /chat/completion
- has different features (chat/completion has hardcoded prompt template)
- support only full featured backends for now
- add chat support here
* TODO Go public
- Rename to YALU ?
- Polish README.md
- Clean history
- Add some more common backends (ollama ?)
- Sync to github
- Announce on /locallama

65
llama_forge_rs/README.md Normal file
View file

@ -0,0 +1,65 @@
# Llama Forge RS App
<!-- Badges -->
![AGPL 3 or later](https://img.shields.io/badge/license-AGPL%203.0%20or%20later-blue)
![🚀 Blazingly fast](https://img.shields.io/badge/%F0%9F%9A%80%20blazingly-fast-brightgreen)
![🪨 Rock Solid](https://img.shields.io/badge/%F0%9F%AA%A8%20rock-solid-violet)
![Zero Bugs🪳](https://img.shields.io/badge/zero-bugs%20%F0%9F%AA%B3-red)
![yes it's](https://img.shields.io/badge/yes%20it's-brightgreen)
![Written in rust😎](https://img.shields.io/badge/written%20in-rust%20%F0%9F%98%8E-orange?logo=rust)
<!-- /Badges -->
## Overview
TODO Decide on projekt name, Llama Forge RS ? YALU ?
## Dependency Installation
### Via Nix Flake
```nix
{
inputs = {
# ...
+ llama-cpp = {
+ url = "git+https://git.vlt81.de/tristan/llama.cpp.git";
+ };
+ # TODO Add nix pacakge for app itself
};
outputs = {
# ....
+ , llama-cpp
, ...
} @ inputs:
let
# Then just use the package, e.g. for home-manager
+ home.packages = [ inputs.llama-cpp.packages.${system}.rocm ];
+ # This might be needed for some AMD GPUS
+ home.sessionVariables = {
+ HSA_OVERRIDE_GFX_VERSION = "10.3.0";
+ };
}
```
## License Notice
TODO Add name hre
Licensed under AGPL 3 or later, see [./LICENSE.md](./LICENSE.md)
TODO one-liner project description here
Copyright (C) 2023-2024 Tristan Druyen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

View file

@ -0,0 +1,121 @@
[
{
"ignore_case": true,
"konto": "600001",
"pattern": "ESF 2311",
"priority": 0,
"werbecode": "000001000028"
},
{
"ignore_case": true,
"konto": "600002",
"pattern": "Für Frieden",
"priority": 0,
"werbecode": "000001000052"
},
{
"ignore_case": true,
"konto": "600003",
"pattern": "Fuer Frieden",
"priority": 0,
"werbecode": "000001000052"
},
{
"ignore_case": true,
"konto": "600004",
"pattern": "r Frieden",
"priority": 0,
"werbecode": "000001000052"
},
{
"ignore_case": true,
"konto": "600005",
"pattern": "ETH 2307",
"priority": 0,
"werbecode": "000001000061"
},
{
"ignore_case": true,
"konto": "600006",
"pattern": "TEPCO",
"priority": 0,
"werbecode": "000001000026"
},
{
"ignore_case": false,
"konto": "600007",
"pattern": "Personal",
"priority": 1,
"werbecode": "000006000006"
},
{
"ignore_case": false,
"konto": "600008",
"pattern": "Fluchtursachen",
"priority": 2,
"werbecode": "000001000066"
},
{
"ignore_case": false,
"konto": "600009",
"pattern": "2305",
"priority": 2,
"werbecode": "000001000053"
},
{
"ignore_case": false,
"konto": "600010",
"pattern": "Planet",
"priority": 2,
"werbecode": "000004000004"
},
{
"ignore_case": true,
"konto": "600011",
"pattern": "Wasserschad",
"priority": 2,
"werbecode": "000001000063"
},
{
"ignore_case": true,
"konto": "600012",
"pattern": "Förderbeitrag",
"priority": 3,
"werbecode": "000003000003"
},
{
"ignore_case": true,
"konto": "600013",
"pattern": "Foerd",
"priority": 3,
"werbecode": "000003000003"
},
{
"ignore_case": false,
"konto": "600014",
"pattern": "Zustift",
"priority": 4,
"werbecode": "000016000011"
},
{
"ignore_case": true,
"konto": "600015",
"pattern": "Konzern-Widerstand 2023",
"priority": 7,
"werbecode": "000001000022"
},
{
"ignore_case": true,
"konto": "600016",
"pattern": "KONZERNKRITIK STAERKEN",
"priority": 8,
"werbecode": "000001000028"
},
{
"ignore_case": false,
"konto": "600099",
"pattern": "Spende",
"priority": 99,
"werbecode": "000001000021"
}
]

View file

@ -0,0 +1,16 @@
services:
llama_forge_rs-release:
image: git.vlt81.de/vault81/llama_forge_rs:dev-release
build:
context: .
args:
BUILD_TYPE: release
BUILD_PKG: llama_forge_rs
llama_forge_rs-debug:
image: git.vlt81.de/vault81/llama_forge_rs:dev-debug
build:
context: .
args:
BUILD_TYPE: debug
BUILD_PKG: llama_forge_rs

109
llama_forge_rs/end2end/package-lock.json generated Normal file
View file

@ -0,0 +1,109 @@
{
"name": "end2end",
"version": "1.0.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "end2end",
"version": "1.0.0",
"license": "ISC",
"devDependencies": {
"@playwright/test": "1.43.1"
}
},
"node_modules/@playwright/test": {
"version": "1.43.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.43.1.tgz",
"integrity": "sha512-HgtQzFgNEEo4TE22K/X7sYTYNqEMMTZmFS8kTq6m8hXj+m1D8TgwgIbumHddJa9h4yl4GkKb8/bgAl2+g7eDgA==",
"dev": true,
"dependencies": {
"playwright": "1.43.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=16"
}
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/playwright": {
"version": "1.43.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.43.1.tgz",
"integrity": "sha512-V7SoH0ai2kNt1Md9E3Gwas5B9m8KR2GVvwZnAI6Pg0m3sh7UvgiYhRrhsziCmqMJNouPckiOhk8T+9bSAK0VIA==",
"dev": true,
"dependencies": {
"playwright-core": "1.43.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=16"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.43.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.43.1.tgz",
"integrity": "sha512-EI36Mto2Vrx6VF7rm708qSnesVQKbxEWvPrfA1IPY6HgczBplDx7ENtx+K2n4kJ41sLLkuGfmb0ZLSSXlDhqPg==",
"dev": true,
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=16"
}
}
},
"dependencies": {
"@playwright/test": {
"version": "1.43.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.43.1.tgz",
"integrity": "sha512-HgtQzFgNEEo4TE22K/X7sYTYNqEMMTZmFS8kTq6m8hXj+m1D8TgwgIbumHddJa9h4yl4GkKb8/bgAl2+g7eDgA==",
"dev": true,
"requires": {
"playwright": "1.43.1"
}
},
"fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"optional": true
},
"playwright": {
"version": "1.43.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.43.1.tgz",
"integrity": "sha512-V7SoH0ai2kNt1Md9E3Gwas5B9m8KR2GVvwZnAI6Pg0m3sh7UvgiYhRrhsziCmqMJNouPckiOhk8T+9bSAK0VIA==",
"dev": true,
"requires": {
"fsevents": "2.3.2",
"playwright-core": "1.43.1"
}
},
"playwright-core": {
"version": "1.43.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.43.1.tgz",
"integrity": "sha512-EI36Mto2Vrx6VF7rm708qSnesVQKbxEWvPrfA1IPY6HgczBplDx7ENtx+K2n4kJ41sLLkuGfmb0ZLSSXlDhqPg==",
"dev": true
}
}
}

View file

@ -0,0 +1,13 @@
{
"name": "end2end",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@playwright/test": "1.43.1"
}
}

View file

@ -0,0 +1,107 @@
import type { PlaywrightTestConfig } from "@playwright/test";
import { devices } from "@playwright/test";
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// require('dotenv').config();
/**
* See https://playwright.dev/docs/test-configuration.
*/
const config: PlaywrightTestConfig = {
testDir: "./tests",
/* Maximum time one test can run for. */
timeout: 30 * 1000,
expect: {
/**
* Maximum time expect() should wait for the condition to be met.
* For example in `await expect(locator).toHaveText();`
*/
timeout: 5000,
},
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: "html",
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,
/* Base URL to use in actions like `await page.goto('/')`. */
// baseURL: 'http://localhost:3000',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: "on-first-retry",
},
/* Configure projects for major browsers */
projects: [
{
name: "chromium",
use: {
...devices["Desktop Chrome"],
},
},
{
name: "firefox",
use: {
...devices["Desktop Firefox"],
},
},
{
name: "webkit",
use: {
...devices["Desktop Safari"],
},
},
/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: {
// ...devices['Pixel 5'],
// },
// },
// {
// name: 'Mobile Safari',
// use: {
// ...devices['iPhone 12'],
// },
// },
/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: {
// channel: 'msedge',
// },
// },
// {
// name: 'Google Chrome',
// use: {
// channel: 'chrome',
// },
// },
],
/* Folder for test artifacts such as screenshots, videos, traces, etc. */
// outputDir: 'test-results/',
/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// port: 3000,
// },
};
export default config;

View file

@ -0,0 +1,12 @@
import { test, expect } from "@playwright/test";
test("homepage has title and links to intro page", async ({ page }) => {
await page.goto("http://localhost:3000/");
await expect(page).toHaveTitle("Welcome to Leptos");
await expect(page.locator("h1")).toHaveText("Welcome to Leptos!");
});
// TODO add a simple e2e smoke test here which chats with the model with a simple question
// TODO add a small (<2GB) testing model

230
llama_forge_rs/flake.lock generated Normal file
View file

@ -0,0 +1,230 @@
{
"nodes": {
"flake-parts": {
"inputs": {
"nixpkgs-lib": "nixpkgs-lib"
},
"locked": {
"lastModified": 1715865404,
"narHash": "sha256-/GJvTdTpuDjNn84j82cU6bXztE0MSkdnTWClUCRub78=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "8dc45382d5206bd292f9c2768b8058a8fd8311d9",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "flake-parts",
"type": "github"
}
},
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1710146030,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_2": {
"inputs": {
"systems": "systems_2"
},
"locked": {
"lastModified": 1705309234,
"narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"llama-cpp": {
"inputs": {
"flake-parts": "flake-parts",
"nixpkgs": "nixpkgs"
},
"locked": {
"lastModified": 1716924132,
"narHash": "sha256-C+4SdaMeKz9APcU/dIV6VAw0k7yYyGaylQTnOjUN5VQ=",
"ref": "refs/heads/master",
"rev": "5f687d392b4d736c3ca5dc4d6778f5713a02ec28",
"revCount": 3027,
"type": "git",
"url": "https://git.vlt81.de/tristan/llama.cpp.git"
},
"original": {
"type": "git",
"url": "https://git.vlt81.de/tristan/llama.cpp.git"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1716509168,
"narHash": "sha256-4zSIhSRRIoEBwjbPm3YiGtbd8HDWzFxJjw5DYSDy1n8=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "bfb7a882678e518398ce9a31a881538679f6f092",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs-lib": {
"locked": {
"lastModified": 1714640452,
"narHash": "sha256-QBx10+k6JWz6u7VsohfSw8g8hjdBZEf8CFzXH1/1Z94=",
"type": "tarball",
"url": "https://github.com/NixOS/nixpkgs/archive/50eb7ecf4cd0a5756d7275c8ba36790e5bd53e33.tar.gz"
},
"original": {
"type": "tarball",
"url": "https://github.com/NixOS/nixpkgs/archive/50eb7ecf4cd0a5756d7275c8ba36790e5bd53e33.tar.gz"
}
},
"nixpkgs-stable": {
"locked": {
"lastModified": 1704067053,
"narHash": "sha256-o5hsB9sBtYT0DBBU1JQ95o3aaANu/97DXz9g0LQh8ns=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "0ef56bec7281e2372338f2dfe7c13327ce96f6bb",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "0ef56bec7281e2372338f2dfe7c13327ce96f6bb",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1715530780,
"narHash": "sha256-bBz4/T/zBzv9Xi5XUlFDeosmSNppLaCQTizMKSksAvk=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "3281bec7174f679eabf584591e75979a258d8c40",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_3": {
"locked": {
"lastModified": 1706487304,
"narHash": "sha256-LE8lVX28MV2jWJsidW13D2qrHU/RUUONendL2Q/WlJg=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "90f456026d284c22b3e3497be980b2e47d0b28ac",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"npmlock2nix": {
"flake": false,
"locked": {
"lastModified": 1673447413,
"narHash": "sha256-sJM82Sj8yfQYs9axEmGZ9Evzdv/kDcI9sddqJ45frrU=",
"owner": "nix-community",
"repo": "npmlock2nix",
"rev": "9197bbf397d76059a76310523d45df10d2e4ca81",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "npmlock2nix",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"llama-cpp": "llama-cpp",
"nixpkgs": "nixpkgs_2",
"nixpkgs-stable": "nixpkgs-stable",
"npmlock2nix": "npmlock2nix",
"rust-overlay": "rust-overlay"
}
},
"rust-overlay": {
"inputs": {
"flake-utils": "flake-utils_2",
"nixpkgs": "nixpkgs_3"
},
"locked": {
"lastModified": 1715566659,
"narHash": "sha256-OpI0TnN+uE0vvxjPStlTzf5RTohIXVSMwrP9NEgMtaY=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "6c465248316cd31502c82f81f1a3acf2d621b01c",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"systems_2": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

174
llama_forge_rs/flake.nix Normal file
View file

@ -0,0 +1,174 @@
{
description = "A Nix-flake-based Rust development environment";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
nixpkgs-stable.url = "github:NixOS/nixpkgs/0ef56bec7281e2372338f2dfe7c13327ce96f6bb";
rust-overlay.url = "github:oxalica/rust-overlay";
flake-utils.url = "github:numtide/flake-utils";
npmlock2nix = {
url = "github:nix-community/npmlock2nix";
flake = false;
};
llama-cpp = {
url = "git+https://git.vlt81.de/tristan/llama.cpp.git";
};
};
outputs =
{ self
, nixpkgs
, nixpkgs-stable
, rust-overlay
, flake-utils
, npmlock2nix
, llama-cpp
}:
flake-utils.lib.eachDefaultSystem
(system:
let
rocmtoolkit_joined = pkgs.symlinkJoin {
name = "rocm-merged";
paths = with pkgs-stable.rocmPackages; [
rocm-core
clr
rccl
miopen
miopengemm
rocrand
rocblas
rocsparse
hipsparse
rocthrust
rocprim
hipcub
roctracer
rocfft
rocsolver
hipfft
hipsolver
hipblas
rocminfo
rocm-thunk
rocm-comgr
rocm-device-libs
rocm-runtime
clr.icd
hipify
];
};
overlays = [
rust-overlay.overlays.default
(final: prev: {
customRustToolchain = prev.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
})
(final: prev: {
npmlock2nix = import npmlock2nix { pkgs = prev; };
})
];
pkgs = import nixpkgs {
inherit system overlays;
};
pkgs-stable = import nixpkgs-stable {
inherit system overlays;
};
customNodeModules = pkgs.npmlock2nix.v2.node_modules {
src = ./.;
nodejs = pkgs.nodejs_20;
};
myllamacpp = llama-cpp.packages.${system}.rocm.override {
rocmTargets = [ "gfx1100" ];
llamaNative = true;
llamaLTO = false;
};
buildInputs = with pkgs; [
atk
cairo
gdk-pixbuf
glib
glibc
gtk3
harfbuzz
libsoup_3
openssl
pango
sqlite
webkitgtk_4_1
zlib
rocmtoolkit_joined
pkgs-stable.clang
pkgs-stable.gzip
pkgs-stable.coreutils
];
in
{
packages = {
cargo-leptos = pkgs.callPackage ./.nix/cargo-leptos.nix { };
};
devShells.default = pkgs.mkShell {
packages = with pkgs;
[
customNodeModules
customRustToolchain
binaryen
cacert
cargo-bloat
cargo-docset
cargo-machete
cargo-limit
cargo-deny
cargo-edit
cargo-watch
cargo-make
cargo-udeps
self.packages.${system}.cargo-leptos
(wasm-bindgen-cli.override {
version = "0.2.92";
hash = "sha256-1VwY8vQy7soKEgbki4LD+v259751kKxSxmo/gqE6yV0=";
cargoHash = "sha256-aACJ+lYNEU8FFBs158G1/JG8sc6Rq080PeKCMnwdpH0=";
})
cargo-outdated
cargo-release
dart-sass
fish
inotify-tools
leptosfmt
mold
nodejs_20
pkg-config
rustywind
sccache
sqlx-cli
unzip
myllamacpp
]
++ buildInputs;
buildInputs = buildInputs;
shellHook = ''
# allow runinng llamafiles
# export PATH=${rocmtoolkit_joined}/bin:$PATH
# export PATH=$PATH:${pkgs-stable.clang}/bin
# export PATH=$PATH:${pkgs-stable.coreutils}/bin
# export PATH=$PATH:${pkgs-stable.gzip}/bin
export HIPCC_COMPILE_FLAGS_APPEND="-I${rocmtoolkit_joined}/include -I${rocmtoolkit_joined}/include/rocblas"
export HIPCC_LINK_FLAGS_APPEND="-L${rocmtoolkit_joined}/lib"
export ROCM_PATH=${rocmtoolkit_joined}
export ROCM_SOURCE_DIR=${rocmtoolkit_joined}
export HSA_OVERRIDE_GFX_VERSION=10.3.0 # this needs to be changed depending on your AMD gpu
# setup node-modules
export NPM_LOCAL_PREFIX=${customNodeModules}/node_modules
(ln -s $NPM_LOCAL_PREFIX ./node_modules 2>/dev/null || unlink ./node_modules) && ln -s $NPM_LOCAL_PREFIX ./node_modules 2>/dev/null
# export NIX_LD_LIBRARY_PATH=${pkgs.lib.makeLibraryPath buildInputs}:$NIX_LD_LIBRARY_PATH
export LEPTOS_SASS_VERSION=1.71.0
export LEPTOS_TAILWIND_VERSION=3.4.3
export MALLOC_CONF=thp:always,metadata_thp:always
'';
};
});
}

View file

@ -0,0 +1,7 @@
-- Add migration script here
CREATE TABLE IF NOT EXISTS settings (
version INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
model_dir TEXT NOT NULL,
default_model TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

View file

@ -0,0 +1,7 @@
-- Add migration script here
CREATE TABLE IF NOT EXISTS backend_process (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
settings_version INTEGER,
status TEXT NOT NULL CHECK( status IN ('waiting_for_start', 'running', 'waiting_for_stop', 'finished', 'failed') ),
FOREIGN KEY(settings_version) REFERENCES settings(version)
);

1507
llama_forge_rs/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,13 @@
{
"name": "llama_forge_rs",
"description": "",
"version": "0.1.0",
"author": "Tristan Druyen <tristan@vault81.mozmail.com>",
"license": "AGPL",
"devDependencies": {
"@tailwindcss/forms": "0.5.7",
"@tailwindcss/typography": "0.5.12",
"daisyui": "4.10.2",
"tailwindcss": "3.4.3"
}
}

View file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View file

@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" class="looka-1j8o68f" viewBox="0 0 200 200">
<path fill="#fd7014" d="m94.04 198.39-75.58-44a11.96 12.06 0 0 1-5.96-10.41V56.03a11.96 12.06 0 0 1 5.96-10.46L94.04 1.62a11.96 12.06 0 0 1 11.96 0l75.54 43.99a11.96 12.06 0 0 1 5.96 10.45v87.92a11.96 12.06 0 0 1-5.96 10.45L106 198.4a11.96 12.06 0 0 1-11.96 0z"/>
<g fill="#222831">
<path d="M85.9 70.8h2.54v-7.77c0-2.85-2.3-5.17-5.12-5.17h-7.7v2.58h3.28a5.15 5.15 0 0 0 4.42 7.76 5.05 5.05 0 0 0 2.56-.71zm-2.57-5.18a2.58 2.58 0 0 1-2.57-2.59 2.57 2.57 0 1 1 5.14 0 2.58 2.58 0 0 1-2.57 2.59zm23.12 3.87c0-3.87-4.15-3.87-6.45-3.87s-6.45 0-6.45 3.87c0 3 .76 5.21 6.44 5.21 5.68 0 6.46-2.22 6.46-5.2zm-10.34 0c0-.83.58-1.29 3.89-1.29 3.3 0 3.87.46 3.87 1.3 0 1.16.76 2.62-3.87 2.62s-3.89-1.46-3.89-2.63zm3.89 7.77c-5.9 0-14.1 6.5-14.1 12.92 0 6.09 5.8 9.09 14.1 9.09s14.1-3 14.1-9.09c0-6.42-8.2-12.93-14.1-12.93zm10.08 8.84c-.78.93-2.62 2.78-4.96 2.78-2.4 0-3.5-1.2-3.85-1.66v-7.24c3.1.6 6.8 3.15 8.81 6.12zm-11.35-6.12v7.24c-.37.48-1.47 1.66-3.87 1.66-2.33 0-4.16-1.86-4.94-2.78 2-2.97 5.7-5.52 8.8-6.12zm1.26 16.7c-5.55 0-11.53-1.17-11.53-6.5 0-.53.1-1.06.25-1.6 1.27 1.29 3.4 2.9 6.15 2.9a7.32 7.32 0 0 0 5.14-1.86 7.32 7.32 0 0 0 5.12 1.85c2.75 0 4.89-1.6 6.17-2.89.15.54.25 1.07.25 1.6 0 5.33-5.99 6.5-11.54 6.5z"/>
<path d="M125.34 46.19c2.8-2.72 6.72-7.45 6.72-12.87 0-8.08-2.67-12.2-2.78-12.37l-.6-.9-1 .45c-7.97 3.57-12.41 10.57-14.57 15.11-3.8-1.52-8.2-2.3-13.12-2.3s-9.3.78-13.11 2.3c-2.15-4.54-6.6-11.54-14.58-15.11l-.98-.44-.6.9c-.12.17-2.78 4.28-2.78 12.36 0 5.42 3.91 10.15 6.72 12.87-3.5 6.05-2.9 12.77-2.9 16.84 0 20.19-2.65 31.4-3.8 37.24l2.53.5c1.17-5.96 3.82-17.34 3.82-37.73 0-5.1-.18-14.62 6.98-21l.53-.47-.12-.7c-.92-5.93-3.58-11.46-5.76-15.2 4.92 3.8 7.75 8.97 9.12 12.15l.52 1.2 1.18-.54A31.54 31.54 0 0 1 100 35.89c5.05 0 9.5.87 13.22 2.59l1.19.54.53-1.2c1.36-3.18 4.19-8.35 9.1-12.15-2.17 3.74-4.84 9.26-5.76 15.2l-.1.7.52.47c7.15 6.38 6.98 15.9 6.98 21 0 20.4 2.65 31.79 3.83 37.73l2.53-.5c-1.17-5.85-3.79-17.04-3.79-37.23 0-4.08.6-10.78-2.91-16.85zm-49.24-2.2c-2.46-2.43-5.6-6.38-5.6-10.69 0-4.29.83-7.31 1.5-9.08 1.98 3 5.8 9.41 7.07 16.38A23.9 23.9 0 0 0 76.1 44zM128 24.22c.67 1.77 1.49 4.8 1.49 9.08 0 4.3-3.14 8.26-5.6 10.7a24.21 24.21 0 0 0-2.96-3.42c1.26-6.93 5.07-13.37 7.07-16.36z"/>
<path d="M111.53 63.03v7.76h2.58v-3.3a5.05 5.05 0 0 0 2.56.71 5.16 5.16 0 0 0 4.41-7.76h3.28v-2.57h-7.7a5.16 5.16 0 0 0-5.13 5.17zm7.7 0a2.57 2.57 0 0 1-2.56 2.59 2.57 2.57 0 0 1-2.56-2.59 2.57 2.57 0 0 1 2.56-2.59 2.57 2.57 0 0 1 2.56 2.6z"/>
</g>
<path fill="#393939" d="M64.4 114.93v1.6h-5.5v-8.29h1.86v6.69zm6.68 0v1.6H65.6v-8.29h1.84v6.69zm6.69 1.6q-.13-.43-.29-.88l-.31-.92h-3.21l-.31.92q-.17.45-.3.87h-1.91l.88-2.47q.41-1.14.8-2.14.4-.99.8-1.9.38-.91.8-1.77h1.76l.8 1.77q.39.9.78 1.9.4 1.01.8 2.14.42 1.13.89 2.47zm-2.22-6.4-.17.48-.28.72-.34.9-.37 1.02h2.34l-.37-1.03q-.17-.49-.35-.9-.17-.4-.27-.71-.1-.31-.19-.49zm7.45-1.89.49.98.58 1.25q.3.66.6 1.39.32.72.56 1.33l.56-1.33.6-1.39.57-1.25.5-.98h1.69q.11.83.22 1.85.1 1.02.17 2.13l.14 2.21q.07 1.11.11 2.1H88l-.09-2.63q-.06-1.42-.18-2.87l-.47 1.12-.52 1.2-.5 1.18-.4.94h-1.3l-.4-.94-.48-1.16-.52-1.22-.47-1.12q-.12 1.45-.18 2.87l-.1 2.62h-1.8l.12-2.08.14-2.22q.07-1.11.19-2.13.11-1.02.22-1.85zm13.96 8.28q-.13-.42-.3-.87l-.3-.92h-3.2l-.33.92-.29.87h-1.9l.88-2.47q.41-1.14.8-2.14.4-.99.79-1.9.4-.91.8-1.77h1.76l.81 1.77q.4.9.78 1.9l.8 2.14q.43 1.13.9 2.47zm-2.22-6.4-.17.49-.28.72-.35.9-.36 1.02h2.34l-.37-1.03-.35-.9q-.17-.4-.27-.71-.09-.31-.2-.49zm8.1 6.4v-8.28h5.52v1.57h-3.65v1.74h3.24v1.55h-3.24v3.42zm8.37-4.14q0 .6.15 1.1.15.5.43.85.27.35.7.54.4.2.91.19.5 0 .92-.19.41-.18.69-.54.28-.36.42-.84.13-.49.15-1.11 0-.63-.15-1.1-.17-.47-.43-.86-.27-.38-.7-.54-.42-.16-.9-.18-.53 0-.93.2-.4.19-.68.54-.28.34-.43.85-.15.5-.15 1.09zm6.27 0q0 1.06-.3 1.87-.32.8-.86 1.35-.55.54-1.31.82-.76.28-1.62.28-.84 0-1.58-.28-.74-.28-1.3-.8-.57-.54-.88-1.37-.31-.83-.33-1.87 0-1.04.34-1.87.35-.84.89-1.36.54-.52 1.3-.82.77-.3 1.56-.27.85 0 1.6.27.75.28 1.3.81.56.53.88 1.37.32.83.31 1.87zm3.95-4.23q1.85 0 2.84.66 1 .66.99 2.07 0 .87-.4 1.42-.39.54-1.15.85.25.31.53.7.28.4.53.85l.52.9q.27.45.46.92h-2.08l-.46-.8-.46-.83q-.23-.4-.49-.75l-.46-.63h-.92v3.01h-1.85v-8.15q.6-.12 1.25-.17.64-.06 1.15-.05zm.12 1.6h-.37q-.16 0-.3.03v2.24h.52q1.04 0 1.5-.26.46-.25.45-.9 0-.6-.46-.86t-1.34-.26zm9.4-.08q-1.3 0-1.87.73-.58.73-.58 1.98 0 .6.15 1.1.15.5.43.86t.7.55q.43.2 1 .2h.53q.23 0 .38-.06v-2.88h1.85v4.1q-.33.14-1.06.29-.74.15-1.82.15-.92 0-1.67-.3-.75-.28-1.3-.83-.54-.54-.8-1.35-.27-.8-.3-1.83 0-1.04.32-1.84t.88-1.35q.55-.56 1.3-.84.75-.3 1.62-.3.58 0 1.04.08.46.07.8.18l.56.2q.2.1.31.18l-.53 1.5q-.38-.22-.86-.35-.49-.14-1.08-.17zm4.32 6.85v-8.28h5.55v1.57h-3.7v1.62h3.28v1.54h-3.28v2h3.97v1.55zm-61.58 4.96q11.36 0 17.4 4.08 6.04 4.07 6.04 12.64 0 5.36-2.44 8.7-2.43 3.34-7.02 5.25 1.52 1.9 3.2 4.36 1.67 2.46 3.31 5.14 1.64 2.68 3.17 5.57 1.52 2.89 2.83 5.7H87.45l-2.8-5.08q-1.43-2.57-2.92-4.99-1.49-2.41-2.94-4.58-1.46-2.17-2.91-3.93h-5.6v18.58H58.91v-50.14q3.7-.72 7.67-1.01 3.97-.3 7.1-.3zm.65 9.76q-1.24 0-2.22.07l-1.85.15v13.8h3.2q6.4 0 9.17-1.63 2.78-1.61 2.78-5.5 0-3.74-2.81-5.3-2.8-1.58-8.27-1.59zm46.88 32.94q2.4 0 3.97-.4 1.56-.4 2.5-1.1.95-.7 1.32-1.65.37-.96.36-2.14 0-2.48-2.32-4.13-2.33-1.65-8-3.56-2.5-.89-4.96-2.02-2.48-1.13-4.44-2.87-1.96-1.73-3.21-4.18-1.25-2.45-1.24-5.98.02-3.54 1.32-6.34 1.3-2.81 3.7-4.8 2.41-2 5.83-3.06 3.42-1.05 7.72-1.06 5.09 0 8.81 1.1 3.72 1.12 6.11 2.43l-3.28 9.01q-2.1-1.1-4.69-1.94-2.59-.84-6.23-.84-4.07 0-5.85 1.14-1.78 1.15-1.78 3.48 0 1.39.65 2.35.64.95 1.84 1.73 1.2.77 2.78 1.38 1.57.62 3.46 1.3 3.93 1.47 6.84 2.89 2.91 1.42 4.85 3.35 1.94 1.92 2.87 4.47.92 2.54.94 6.23 0 7.12-4.95 11.05-4.96 3.92-14.92 3.92-3.34 0-6.04-.4-2.69-.4-4.77-1-2.08-.58-3.57-1.24-1.49-.66-2.5-1.25l3.2-9.1q2.25 1.25 5.56 2.24 3.32 1 8.12 1z"/>
</svg>

After

Width:  |  Height:  |  Size: 5.7 KiB

View file

@ -0,0 +1,21 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": ["config:best-practices"],
"prConcurrentLimit": 2,
"prHourlyLimit": 8,
"semanticCommits": "enabled",
"packageRules": [
{
"matchUpdateTypes": ["minor", "patch", "pin"],
"matchCurrentVersion": "!/^0/",
"automerge": true
},
{
"matchUpdateTypes": ["patch", "pin", "digest"],
"automerge": true
}
],
"nix": {
"enabled": true
}
}

View file

@ -0,0 +1,16 @@
[toolchain]
channel = "nightly-2024-04-14"
targets = [
"x86_64-unknown-linux-gnu",
"wasm32-unknown-unknown",
"x86_64-pc-windows-msvc",
]
components = [
"cargo",
"rustfmt",
"rust-analyzer",
"rust-src",
"rustc-codegen-cranelift",
"rustc-dev",
]
profile = "default"

View file

@ -0,0 +1,23 @@
edition = "2021"
max_width = 100
tab_spaces = 4
# unstable
format_macro_bodies = true
format_macro_matchers = true
format_strings = true
group_imports = "StdExternalCrate"
imports_granularity = "Crate"
imports_layout = "HorizontalVertical"
overflow_delimited_expr = true
reorder_impl_items = true
struct_field_align_threshold = 4
struct_lit_single_line = false
trailing_comma = "Vertical"
unstable_features = true
use_field_init_shorthand = true
use_try_shorthand = true
wrap_comments = false
# format_brace_macros = true

View file

@ -0,0 +1,190 @@
use std::time::Duration;
use leptos::*;
use serde::{Deserialize, Serialize};
use super::backend_settings::BackendSettings;
use crate::app::components::FormControl;
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct BackendProcess {
id: i64,
#[sqlx(flatten)]
settings: BackendSettings,
status: ProcessStatus,
}
/// The `ProcessStatus` enum represents the various states a process can be in. It includes the following states:
/// - `WaitingForStart`: The process is waiting to be started.
/// - `Running`: The process is currently running.
/// - `WaitingForStop`: The process is waiting to be stopped.
/// - `Finished`: The process has completed its execution successfully.
/// - `Failed`: The process has failed or encountered an error during execution.
/// This enum is used to keep track of the state of a process in a backend application, allowing for proper management and control over the process lifecycle.
#[derive(
Default, PartialEq, Debug, Clone, Serialize, Deserialize, sqlx::Type, strum::EnumString,
)]
#[sqlx(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ProcessStatus {
#[default]
WaitingForStart,
Running,
WaitingForStop,
Finished,
Failed,
}
/// CHecks the db every 100ms to see if stuff has to be started
#[cfg(feature = "ssr")]
pub async fn run_starter_task(pool: sqlx::SqlitePool) {
use tokio::{
time::{self, Instant},
try_join,
};
use tokio_stream::{wrappers::IntervalStream, StreamExt};
use crate::server::backends::BackendService;
let _ = tracing::debug_span!("starter_task");
tracing::debug!("Starter task started");
let service_handle = BackendService::new();
let mut stream = IntervalStream::new(time::interval(Duration::from_millis(1000)));
while let Some(instant) = stream.next().await {
tracing::debug!("fire; instant={:?}", instant);
let waiting_to_start: Vec<BackendProcess> = sqlx::query_as(
"SELECT id, status,
se.version, se.model_dir, se.default_model, se.created_at
FROM backend_process INNER JOIN settings AS se
ON backend_process.settings_version = se.version
WHERE status == ?",
)
.bind(ProcessStatus::WaitingForStart)
.fetch_all(&pool)
.await
.unwrap();
let waiting_to_stop: Vec<BackendProcess> = sqlx::query_as(
"SELECT id, status,
se.version, se.model_dir, se.default_model, se.created_at
FROM backend_process INNER JOIN settings AS se
ON backend_process.settings_version = se.version
WHERE status == ?",
)
.bind(ProcessStatus::WaitingForStop)
.fetch_all(&pool)
.await
.unwrap();
tracing::debug!(?waiting_to_start, ?waiting_to_stop);
use futures::future::FutureExt;
for to_stop in waiting_to_stop.into_iter() {
tracing::debug!(?to_stop);
let update_query_fut = sqlx::query!(
"UPDATE backend_process
SET status == ?
WHERE id == ?",
ProcessStatus::Finished,
to_stop.id
)
.execute(&pool)
.map(|f| f.map_err(|_e| anyhow::Error::msg("update fail")));
let stop_fut = service_handle.stop();
tracing::debug!(msg = "Stopping", ?to_stop);
try_join!(update_query_fut, stop_fut).expect("stop fail");
tracing::debug!(msg = "Stopped!", ?to_stop);
}
for to_start in waiting_to_start.into_iter() {
// TODO Pass args to backend
// TODO Save Services tehrefore allow multiples
tracing::debug!(?to_start);
let update_query_fut = sqlx::query!(
"UPDATE backend_process
SET status == ?
WHERE id == ?",
ProcessStatus::Running,
to_start.id
)
.execute(&pool)
.map(|f| f.map_err(|_e| anyhow::Error::msg("update fail")));
tracing::debug!(msg = "Starting", ?to_start);
let start_fut = service_handle.start();
try_join!(update_query_fut, start_fut).expect("start fail");
tracing::debug!(msg = "Started!", ?to_start);
}
tracing::debug!(msg="Starter task iteration finished", iteration_dur=?Instant::now().duration_since(instant))
}
}
/// Starts a new process and updates the process status.
#[server]
pub async fn start_process() -> Result<(), ServerFnError> {
use crate::server::pool;
let pool = pool()?;
// Set all existing processes to Finished
sqlx::query!(
"UPDATE backend_process SET status = 'waiting_for_stop' WHERE status != 'finished'"
)
.execute(&pool)
.await?;
// Get the current newest settings version
let settings_version =
sqlx::query_scalar!("SELECT version FROM settings ORDER BY version DESC LIMIT 1")
.fetch_one(&pool)
.await?;
// Create a new ProcessStatus with the current newest settings version and initial status of waiting
sqlx::query!(
"INSERT INTO backend_process (settings_version, status) VALUES (?, 'waiting_for_start')",
settings_version
)
.execute(&pool)
.await?;
Ok(())
}
/// Stops all processes and updates the process status.
#[server]
pub async fn stop_process() -> Result<(), ServerFnError> {
use crate::server::pool;
let pool = pool()?;
// Set all processes to finished
sqlx::query!("UPDATE backend_process SET status = 'waiting_for_stop'")
.execute(&pool)
.await?;
Ok(())
}
/// Fetches the status of the newest process.
#[server(ProcessStatusFn)]
pub async fn process_status() -> Result<ProcessStatus, ServerFnError> {
use crate::server::pool;
let pool = pool()?;
let status: Option<ProcessStatus> =
sqlx::query_scalar!("SELECT status FROM backend_process ORDER BY id DESC LIMIT 1")
.fetch_optional(&pool)
.await?
.map(|str| str.parse())
.transpose()?;
match status {
Some(status) => Ok(status),
None => Ok(ProcessStatus::Finished),
}
}

View file

@ -0,0 +1,71 @@
use leptos::*;
use leptos_router::*;
use serde::{Deserialize, Serialize};
use crate::app::components::{svgs::*, FormControl};
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct BackendSettings {
version: i64, // auto-increments, the current settings are the highest version
model_dir: String,
default_model: String,
created_at: chrono::NaiveDateTime,
}
/// Returns the initial default directory for model files. ($PWD/models)
#[server]
async fn default_model_dir() -> Result<String, ServerFnError> {
let pwd = std::env::current_dir()?.to_string_lossy().to_string();
let default_dir = format!("{}/models", pwd);
Ok(default_dir)
}
/// Fetches the latest backend settings from the database.
#[server]
async fn load_backend_settings() -> Result<BackendSettings, ServerFnError> {
use crate::server::pool;
tracing::debug!(msg = "Load settings");
let pool = pool()?;
let settings = sqlx::query_as!(
BackendSettings,
"SELECT version, model_dir, default_model, created_at FROM settings ORDER BY version DESC \
LIMIT 1"
)
.fetch_optional(&pool)
.await?;
match settings {
Some(settings) => Ok(settings),
None => Err(ServerFnError::ServerError("Settings not found".to_string())),
}
}
/// Updates the backend settings with new model directory and default model.
#[server(UpdateSettings)]
async fn update_settings(model_dir: String, default_model: String) -> Result<(), ServerFnError> {
use crate::server::pool;
tracing::debug!(msg = "Updating settings", ?model_dir, ?default_model);
let pool = pool()?;
let result = {
sqlx_macros::expand_query!(
source = "INSERT INTO settings (model_dir, default_model) VALUES (?, ?)",
args = [model_dir, default_model,]
)
}
.execute(&pool)
.await?;
if result.rows_affected() == 0 {
return Err(ServerFnError::ServerError(
"Failed to create new settings".to_string(),
));
}
Ok(())
}

View file

@ -0,0 +1,33 @@
use bytes::Bytes;
use leptos::*;
use server_fn::codec::{ByteStream, Streaming};
use uuid::Uuid;
use crate::api::{ChannelMessage, ChatMessage};
#[server(name=TestServerFn, output = Streaming)]
pub async fn stream_chat(id: Uuid, history: Vec<ChatMessage>) -> Result<ByteStream, ServerFnError> {
use tokio::sync::mpsc;
use tokio_stream::{wrappers::ReceiverStream, StreamExt};
use crate::server::backends::{llama_chat, ChatService};
let (tx, rx) = mpsc::channel::<ChannelMessage>(8);
let service = llama_chat::LlamaService::new(id);
let _handle = tokio::spawn(service.chat_request(history, tx));
let broadcast_receive_stream = ReceiverStream::new(rx)
.map(|msg| {
tracing::trace!(?msg);
serde_json::to_string(&msg).unwrap()
})
.map(|string| {
let bytes = Bytes::from(string.as_bytes().to_vec());
Ok(bytes)
});
let text_stream = ByteStream::new(broadcast_receive_stream);
Ok(text_stream)
}

View file

@ -0,0 +1,74 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
mod backend_process;
mod backend_settings;
mod chat;
// pub mod backend_process;
// pub mod backend_settings;
// pub mod chat;
pub use backend_process::*;
pub use backend_settings::*;
pub use chat::*;
#[derive(Clone, Debug, Serialize, Deserialize, Hash, PartialEq)]
pub enum ChatRole {
System,
User,
Assistant,
}
impl From<ChatRole> for String {
fn from(val: ChatRole) -> Self {
match val {
ChatRole::System => "system",
ChatRole::User => "user",
ChatRole::Assistant => "assistand",
}
.to_string()
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Hash, PartialEq)]
pub struct ChatMessage {
pub id: Uuid,
pub role: ChatRole,
pub content: String,
_meta: String,
}
impl ChatMessage {
pub fn new(role: ChatRole, content: String) -> Self {
Self {
id: Uuid::now_v7(),
role,
content,
_meta: "".to_string(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Hash, PartialEq)]
pub enum ChannelMessage {
Token(String),
Stop,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Chat {
// sampler_settings: SamplerSettings,
pub id: Uuid,
pub history: Vec<ChatMessage>,
_meta: String,
}
impl Chat {
pub fn new(id: Uuid, history: Vec<ChatMessage>, meta: String) -> Self {
Self {
id,
history,
_meta: meta,
}
}
}

View file

@ -0,0 +1,24 @@
use leptos::*;
pub mod svgs;
#[component]
pub fn FormControl(label: &'static str, children: Children) -> impl IntoView {
view! {
<div class="w-full form-control">
<label class="label">
<span class="label-text">{label}</span>
{children()}
</label>
</div>
}
}
#[component]
pub fn Card(children: Children) -> impl IntoView {
view! {
<div class="overflow-y-scroll flex-col-reverse shadow-xl max-h-[80dvh] size-full bg-base-300 card">
<div class="card-body">{children()}</div>
</div>
}
}

View file

@ -0,0 +1,229 @@
use leptos::*;
#[component]
pub fn SaveSvg() -> impl IntoView {
view! {
<svg
class="w-5 h-5"
stroke-width="1.5"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
color="currentColor"
>
<path
d="M3 7.5V5C3 3.89543 3.89543 3 5 3H16.1716C16.702 3 17.2107 3.21071 17.5858 3.58579L20.4142 6.41421C20.7893 6.78929 21 7.29799 21 7.82843V19C21 20.1046 20.1046 21 19 21H5C3.89543 21 3 20.1046 3 19V16.5"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
<path
d="M6 21V17"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
<path
d="M18 21V13.6C18 13.2686 17.7314 13 17.4 13H15"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
<path
d="M16 3V8.4C16 8.73137 15.7314 9 15.4 9H13.5"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
<path
d="M8 3V6"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
<path
d="M1 12H12M12 12L9 9M12 12L9 15"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
</svg>
}
}
#[component]
pub fn TrashSvg() -> impl IntoView {
view! {
<svg
class="w-5 h-5"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="1.5"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M20 9L18.005 20.3463C17.8369 21.3026 17.0062 22 16.0353 22H7.96474C6.99379 22 6.1631 21.3026 5.99496 20.3463L4 9"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
<path
d="M21 6L15.375 6M3 6L8.625 6M8.625 6V4C8.625 2.89543 9.52043 2 10.625 2H13.375C14.4796 2 15.375 2.89543 15.375 4V6M8.625 6L15.375 6"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
</svg>
}
}
#[component]
pub fn SendSvg() -> impl IntoView {
view! {
<svg
class="w-5 h-5"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
stroke-width="1.5"
style="--darkreader-inline-color: #e8e6e3;"
data-darkreader-inline-color=""
>
<g clip-path="url(#clip0_4086_8473)">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M1.84647 7.15123C1.54566 7.21608 1.31498 7.45811 1.26464 7.7617C1.2143 8.06528 1.35452 8.36881 1.6183 8.52729L8.13474 12.4421L14.3544 8.08705C14.6938 7.84947 15.1614 7.93193 15.399 8.27123C15.6366 8.61054 15.5541 9.0782 15.2148 9.31578L8.99537 13.6707L10.4455 21.1339C10.5042 21.436 10.7415 21.6715 11.044 21.7281C11.3465 21.7846 11.6528 21.6506 11.8166 21.3901L22.7919 3.93893C22.9526 3.68349 22.9445 3.35665 22.7714 3.10947C22.5983 2.86228 22.294 2.7429 21.999 2.80649L1.84647 7.15123Z"
fill="currentColor"
></path>
</g>
<defs>
<clipPath id="clip0_4086_8473">
<rect width="24" height="24" fill="white"></rect>
</clipPath>
</defs>
</svg>
}
}
#[component]
pub fn RefreshSvg() -> impl IntoView {
view! {
<svg
class="w-5 h-5"
stroke="currentColor"
stroke-width="1.5"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M21.1679 8C19.6247 4.46819 16.1006 2 11.9999 2C6.81459 2 2.55104 5.94668 2.04932 11"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
<path
d="M17 8H21.4C21.7314 8 22 7.73137 22 7.4V3"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
<path
d="M2.88146 16C4.42458 19.5318 7.94874 22 12.0494 22C17.2347 22 21.4983 18.0533 22 13"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
<path
d="M7.04932 16H2.64932C2.31795 16 2.04932 16.2686 2.04932 16.6V21"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
</svg>
}
}
#[component]
pub fn HamburgerSvg() -> impl IntoView {
view! {
<svg
xmlns="http://www.w3.org/2000/svg"
class="w-5 h-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 6h16M4 12h16M4 18h7"
></path>
</svg>
}
}
#[component]
pub fn CheckmarkSvg() -> impl IntoView {
view! {
<svg
class="w-4 h-4"
stroke="currentColor"
stroke-width="1.5"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M7 12.5L10 15.5L17 8.5"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
<path
d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
</svg>
}
}
#[component]
pub fn PencilSvg() -> impl IntoView {
view! {
<svg
class="w-4 h-4"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="1.5"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M14.3632 5.65156L15.8431 4.17157C16.6242 3.39052 17.8905 3.39052 18.6716 4.17157L20.0858 5.58579C20.8668 6.36683 20.8668 7.63316 20.0858 8.41421L18.6058 9.8942M14.3632 5.65156L4.74749 15.2672C4.41542 15.5993 4.21079 16.0376 4.16947 16.5054L3.92738 19.2459C3.87261 19.8659 4.39148 20.3848 5.0115 20.33L7.75191 20.0879C8.21972 20.0466 8.65806 19.8419 8.99013 19.5099L18.6058 9.8942M14.3632 5.65156L18.6058 9.8942"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
></path>
</svg>
}
}

View file

@ -0,0 +1,80 @@
use http::status::StatusCode;
use leptos::*;
#[cfg(feature = "ssr")]
use leptos_axum::ResponseOptions;
use thiserror::Error;
use crate::app::{components::Card, pages::Main};
#[derive(Clone, Debug, Error)]
pub enum AppError {
#[error("Not Found")]
NotFound,
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
}
}
}
// A basic function to display errors served by the error boundaries.
// Feel free to do more complicated things here than just displaying the error.
#[component]
pub fn ErrorTemplate(
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional)] errors: Option<RwSignal<Errors>>,
) -> impl IntoView {
let errors = match outside_errors {
Some(e) => create_rw_signal(e),
None => match errors {
Some(e) => e,
None => panic!("No Errors found and we expected errors!"),
},
};
// Get Errors from Signal
let errors = errors.get_untracked();
// Downcast lets us take a type that implements `std::error::Error`
let errors: Vec<AppError> = errors
.into_iter()
.filter_map(|(_k, v)| v.downcast_ref::<AppError>().cloned())
.collect();
tracing::error!("Errors: {errors:#?}");
// Only the response code for the first error is actually sent from the server
// this may be customized by the specific application
#[cfg(feature = "ssr")]
{
let response = use_context::<ResponseOptions>();
if let Some(response) = response {
response.set_status(errors[0].status_code());
}
}
view! {
<Main>
<Card>
<h1>{if errors.len() > 1 { "Errors" } else { "Error" }}</h1>
<For
// a function that returns the items we're iterating over; a signal is fine
each=move || { errors.clone().into_iter().enumerate() }
// a unique key for each item as a reference
key=|(index, _error)| *index
// renders each item to a view
children=move |error| {
tracing::error!(? error);
let error_string = error.1.to_string();
let error_code = error.1.status_code();
view! {
<h2>{error_code.to_string()}</h2>
<p>"Error: " {error_string}</p>
}
}
/>
</Card>
</Main>
}
}

View file

@ -0,0 +1,50 @@
use std::sync::Arc;
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
pub(crate) mod components;
pub(crate) mod error_template;
pub(crate) mod pages;
use self::{
error_template::{AppError, ErrorTemplate},
pages::*,
};
#[derive(Clone, Debug, PartialEq)]
pub struct RefreshGen(pub i64);
#[island]
pub fn App() -> impl IntoView {
let span = tracing::info_span!("app");
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();
let refresh_gen = create_rw_signal(RefreshGen(0));
provide_context(refresh_gen);
provide_context(Arc::new(span));
view! {
<Stylesheet id="leptos" href="/pkg/llama_forge_rs.css"/>
// sets the document title
<Title text="LLama Forge RS"/>
<Router fallback=|| {
let mut outside_errors = Errors::default();
outside_errors.insert_with_default_key(AppError::NotFound);
view! { <ErrorTemplate outside_errors/> }.into_view()
}>
<main>
<Routes>
<Route path="" view=MainPage>
<Route path="/chat" view=ChatPage/>
<SettingsRoutes/>
</Route>
</Routes>
</main>
</Router>
}
}

View file

@ -0,0 +1,320 @@
use std::{
hash::{DefaultHasher, Hash, Hasher},
ops::Deref,
};
use bytes::Bytes;
use leptos::*;
use uuid::Uuid;
use crate::{
api::{stream_chat, ChannelMessage, ChatMessage, ChatRole},
app::components::{svgs::*, Card},
};
#[component]
fn ChatMessageBubble(
msg: RwSignal<ChatMessage>,
history: RwSignal<Vec<RwSignal<ChatMessage>>>,
) -> impl IntoView {
let (edit_mode, set_edit_mode) = create_signal(false);
let _ = create_effect(move |_| tracing::debug!(edit_mode=%edit_mode()));
let role = match msg.get().role {
ChatRole::System => "System",
ChatRole::User => "User",
ChatRole::Assistant => "Assistant",
};
let chat_class = match msg.get().role {
ChatRole::System => "chat-start",
ChatRole::Assistant => "chat-start",
ChatRole::User => "chat-end",
};
let textarea_ref = NodeRef::<html::P>::new();
let editable_p = move || {
let mode = if edit_mode.get() { "true" } else { "false" };
view! {
<p node_ref=textarea_ref contenteditable=move || { mode }>
<span inner_html=msg.get().content.clone()></span>
</p>
}
};
let enter_edit_mode = move |_ev| {
set_edit_mode.set(true);
textarea_ref().expect("").deref().clone().focus().unwrap();
};
let exit_edit_mode = move |_ev| {
let inner_text = textarea_ref().expect("").deref().clone().inner_text();
msg.update(move |msg| msg.content = inner_text);
set_edit_mode.set(false);
};
let trash_message = move || {
let id = msg.get().id;
history.update(move |his| {
his.retain(|elem| elem.get().id != id);
});
};
let edit_button = move || {
if edit_mode() {
view! {
<button
on:click=exit_edit_mode
class="absolute top-2 right-2 btn btn-xs btn-ghost btn-circle"
>
<CheckmarkSvg/>
</button>
}
.into_view()
} else {
view! {
<button
on:click=enter_edit_mode
class="absolute top-2 right-2 btn btn-xs btn-ghost btn-circle"
>
<PencilSvg/>
</button>
}
.into_view()
}
};
let trash_button = move || {
if msg().role != ChatRole::System && !edit_mode() {
view! {
<button
on:click=move |_e| trash_message()
class="absolute right-2 bottom-2 btn btn-xs btn-ghost btn-circle"
>
<TrashSvg/>
</button>
}
.into_view()
} else {
"".into_view()
}
};
view! {
<div class=format!("chat {chat_class}")>
<div class="chat-header">
<div class="flex flex-nowrap">
<p class="grow">{role}</p>
</div>
</div>
<div class="chat-bubble">
{edit_button} {trash_button} <div class="flex flex-nowrap w-full h-full">
<div>{editable_p}</div>
// as the edit/trash buttons are absolutely positions this makes sure they dont overlap with text
// TODO move them here ?
<div class="w-6 h-12 shrink-0">""</div>
</div>
</div>
</div>
}
}
#[component]
pub fn ChatHistory(
history: RwSignal<Vec<RwSignal<ChatMessage>>>,
response: RwSignal<String>,
receiving_response: RwSignal<bool>,
) -> impl IntoView {
let streaming_response_elem = move || {
if receiving_response() {
view! {
<div class="chat chat-start">
<div class="chat-header">"Assistant"</div>
<div class="chat-bubble">
<span inner_html=response></span>
<span class="loading loading-ball loading-xs"></span>
</div>
</div>
}
.into_view()
} else {
view! { <></> }.into_view()
}
};
view! {
<div class="flex flex-col flex-nowrap p-2">
<For
each=move || history().into_iter()
key=|entry| {
let mut s = DefaultHasher::new();
entry.get().hash(&mut s);
s.finish()
}
children=move |msg| {
view! { <ChatMessageBubble msg history/> }
}
/>
{streaming_response_elem}
</div>
}
}
#[component]
fn ChatPrompt(
receiving_response: RwSignal<bool>,
history: RwSignal<Vec<RwSignal<ChatMessage>>>,
response: RwSignal<String>,
) -> impl IntoView {
let stream_completion = create_action(move |id: &Uuid| {
use futures_util::StreamExt;
let id = *id;
let history_inner = history();
let handle_stop = move || {
history.update(move |vec| {
let msg = ChatMessage::new(ChatRole::Assistant, response.get_untracked());
vec.push(create_rw_signal(msg));
});
response.set("".to_string());
receiving_response.set(false);
};
let handle_token = move |string: String| {
response.update(move |resp| {
resp.push_str(string.as_str());
});
};
let handle_chunk = move |chunk: Bytes| {
tracing::debug!(?chunk);
let deserializer = serde_json::Deserializer::from_slice(&chunk);
for msg in deserializer.into_iter::<ChannelMessage>() {
tracing::debug!(?msg);
match msg {
Ok(ChannelMessage::Stop) => handle_stop(),
Ok(ChannelMessage::Token(string)) => handle_token(string),
Err(err) => {
tracing::error!(?err);
panic!("Unknown stream errror")
}
};
}
};
async move {
let his_inner = history_inner
.into_iter()
.map(|sig| sig.get())
.collect::<Vec<_>>();
let res_stream = stream_chat(id, his_inner).await;
if let Ok(stream) = res_stream {
let mut stream = stream.into_inner();
tracing::debug!("Stream start");
while let Some(Ok(chunk)) = stream.next().await {
handle_chunk(chunk);
}
tracing::debug!("Stream end");
}
}
});
let prompt_input_element: NodeRef<html::Input> = create_node_ref();
let submit_chat = move || {
receiving_response.set(true);
let input = prompt_input_element().expect("<input> should be mounted");
let value = input.value();
input.set_value("");
if !value.is_empty() {
let new_chat_entry = ChatMessage::new(ChatRole::User, value.clone());
let new_entry_sig = create_rw_signal(new_chat_entry);
history.update(move |hist| hist.push(new_entry_sig));
}
stream_completion.dispatch(Uuid::now_v7());
};
let submit_on_enter = move |ev: web_sys::KeyboardEvent| {
const ENTER_KEY: u32 = 13;
let key_code = ev.key_code();
let shift_key = ev.shift_key();
if key_code == ENTER_KEY && !shift_key {
submit_chat()
}
};
let refresh_last_message = move |ev: web_sys::MouseEvent| {
ev.prevent_default();
receiving_response.set(true);
history.update(move |hist| {
hist.pop();
});
stream_completion.dispatch(Uuid::now_v7());
};
view! {
<div class="flex-nowrap justify-around p-2 card-actions">
<input
class="w-full input grow input-bordered input-primary"
type="text"
placeholder="Type here"
node_ref=prompt_input_element
on:keyup=submit_on_enter
/>
<button
type="submit"
class="btn btn-primary"
class:btn-disabled=receiving_response
on:click=move |ev| {
ev.prevent_default();
submit_chat()
}
>
<SendSvg/>
</button>
<button
on:click=refresh_last_message
class="btn btn-ghost"
class:btn-disabled=move || {
receiving_response()
|| history().last().unwrap().get().role != ChatRole::Assistant
}
>
<RefreshSvg/>
</button>
</div>
}
}
#[component]
pub fn ChatPage() -> impl IntoView {
let initial_history = vec![create_rw_signal(ChatMessage::new(
ChatRole::System,
"You are an helpful AI-based assistant.".to_string(),
))];
let history = create_rw_signal(initial_history);
let response = create_rw_signal("".to_string());
let receiving_response = create_rw_signal(false);
view! {
<Card>
<div class="flex flex-col justify-between h-full">
<ChatHistory receiving_response history response/>
<ChatPrompt receiving_response history response/>
</div>
</Card>
}
}

View file

@ -0,0 +1,71 @@
use leptos::*;
// use leptos_meta::*;
use leptos_router::*;
use crate::app::components::svgs::HamburgerSvg;
#[component]
fn Navbar() -> impl IntoView {
view! {
<div class="navbar bg-base-100">
<div class="navbar-start">
<div class="dropdown">
<div tabindex="0" role="button" class="btn btn-ghost btn-circle">
<HamburgerSvg/>
</div>
<ul
tabindex="0"
class="p-2 mt-3 w-52 border-2 shadow menu menu-sm dropdown-content z-[1] bg-base-100 rounded-box border-base-200"
>
<li>
<a href="/chat">"Chat"</a>
</li>
<li>
<a href="/settings/backend">"Settings"</a>
</li>
</ul>
</div>
</div>
<div class="navbar-center">
<a class="text-xl btn btn-ghost">"LLama Forge RS🦙🔨🦀"</a>
</div>
<div class="navbar-end">
<button class="btn btn-ghost btn-circle">
<img class="w-12 h-12" src="/logo.svg"/>
</button>
</div>
</div>
}
}
#[component]
fn Footer() -> impl IntoView {
view! {
<footer class="items-center p-2 footer bg-neutral text-neutral-content">
<nav class="grid-flow-col gap-2 md:justify-self-end md:place-self-center">
<a href="/about">"About"</a>
</nav>
</footer>
}
}
#[component]
pub fn Main(children: Children) -> impl IntoView {
view! {
<div class="flex flex-col w-screen h-screen">
<Navbar/>
<div class="grid place-items-center p-4 grow">{children()}</div>
// <Footer/>
</div>
}
}
#[component]
pub fn MainPage() -> impl IntoView {
view! {
<Main>
<Outlet/>
</Main>
}
}

View file

@ -0,0 +1,7 @@
mod chat;
mod main;
pub mod settings;
pub use chat::*;
pub use main::*;
pub use settings::*;

View file

@ -0,0 +1,139 @@
use leptos::*;
use leptos_router::*;
use serde::{Deserialize, Serialize};
use crate::app::components::{svgs::*, FormControl};
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct BackendSettings {
version: i64, // auto-increments, the current settings are the highest version
model_dir: String,
default_model: String,
created_at: chrono::NaiveDateTime,
}
/// Returns the initial default directory for model files. ($PWD/models)
#[server]
async fn default_model_dir() -> Result<String, ServerFnError> {
let pwd = std::env::current_dir()?.to_string_lossy().to_string();
let default_dir = format!("{}/models", pwd);
Ok(default_dir)
}
/// Fetches the latest backend settings from the database.
#[server]
async fn load_backend_settings() -> Result<BackendSettings, ServerFnError> {
use crate::server::pool;
tracing::debug!(msg = "Load settings");
let pool = pool()?;
let settings = sqlx::query_as!(
BackendSettings,
"SELECT version, model_dir, default_model, created_at FROM settings ORDER BY version DESC \
LIMIT 1"
)
.fetch_optional(&pool)
.await?;
match settings {
Some(settings) => Ok(settings),
None => Err(ServerFnError::ServerError("Settings not found".to_string())),
}
}
/// Updates the backend settings with new model directory and default model.
#[server(UpdateSettings)]
async fn update_settings(model_dir: String, default_model: String) -> Result<(), ServerFnError> {
use crate::server::pool;
tracing::debug!(msg = "Updating settings", ?model_dir, ?default_model);
let pool = pool()?;
let result = {
sqlx_macros::expand_query!(
source = "INSERT INTO settings (model_dir, default_model) VALUES (?, ?)",
args = [model_dir, default_model,]
)
}
.execute(&pool)
.await?;
if result.rows_affected() == 0 {
return Err(ServerFnError::ServerError(
"Failed to create new settings".to_string(),
));
}
Ok(())
}
/// A form component for updating the backend settings.<|im_end|>
#[component]
pub fn SettingsForm() -> impl IntoView {
let update_settings_action = create_server_action::<UpdateSettings>();
let backend_settings_res = create_local_resource(
|| (),
|_| async move {
let settings = load_backend_settings().await;
match settings {
Ok(settings) => settings,
Err(_) => {
let default_dir = default_model_dir().await.unwrap_or("".to_string());
BackendSettings {
version: 1,
model_dir: default_dir,
default_model: "meta-llama-3-8b-instruct-imat-IQ3_XXS.gguf".to_string(),
created_at: chrono::Utc::now().naive_utc(),
}
}
}
},
);
let model_dir = move || {
if let Some(setting) = backend_settings_res.get() {
setting.model_dir.to_string()
} else {
"loading".to_string()
}
};
let default_model = move || {
if let Some(setting) = backend_settings_res.get() {
setting.default_model.to_string()
} else {
"loading".to_string()
}
};
view! {
<ActionForm action=update_settings_action>
<FormControl label="Default Model">
<input
type="text"
name="default_model"
placeholder="meta-llama-3-8b-instruct-imat-IQ3_XXS.gguf"
value=default_model
class="grow max-w-[75%] input input-xs input-bordered"
/>
</FormControl>
<FormControl label="model_dir">
<input
type="text"
name="model_dir"
placeholder="/opt/ai/models"
value=model_dir
class="grow max-w-[75%] input input-xs input-bordered"
/>
</FormControl>
<div class="w-full form-control">
<button class="btn btn-primary" type="submit">
<SaveSvg/>
</button>
</div>
</ActionForm>
}
}

View file

@ -0,0 +1,96 @@
use leptos::*;
use leptos_router::*;
use crate::app::{components::svgs::*, RefreshGen};
mod backend;
pub mod process;
use backend::SettingsForm;
use process::ProcessForm;
#[component]
fn TabButton(path: &'static str, label: &'static str) -> impl IntoView {
let current_path = use_location().pathname;
view! {
<a role="tab" class="tab" class:tab-active=move || current_path.get() == path href=path>
{label}
</a>
}
}
#[component]
fn TabCard(children: Children) -> impl IntoView {
view! {
<div class="rounded-none !rounded-b-lg !rounded-tr-lg overflow-y-scroll flex-col-reverse shadow-xl max-h-[85dvh] size-full bg-base-300 card">
<div class="card-body">{children()}</div>
</div>
}
}
#[component]
fn BackendSettingsPage() -> impl IntoView {
view! {
<div class="flex justify-around">
<div class="flex flex-col p-4 w-1/3">
<ProcessForm/>
</div>
<div class="flex flex-col p-4 w-2/3">
<SettingsForm/>
</div>
</div>
}
}
#[component]
fn ModelSettingsPage() -> impl IntoView {
view! {
<div>
<p>"modellist here"</p>
<p>"TODO"</p>
</div>
}
}
#[component]
fn SettingsPage() -> impl IntoView {
let gen = use_context::<RwSignal<RefreshGen>>().expect("to have found the setter provided");
let increment_gen = move |_ev| {
gen.update(|gen| *gen = RefreshGen(gen.0 + 1));
};
view! {
<div class="flex flex-col size-full">
<div class="flex justify-between">
<div
role="tablist"
class="shadow-xl border-b-2 border-base-200 bg-base-300 rounded-none !rounded-t-lg shrink tabs tabs-boxed"
>
<TabButton path="/settings/backend" label="Backend"/>
<TabButton path="/settings/model" label="Model"/>
</div>
<div class="shadow-xl border-b-2 border-base-200 bg-base-300 rounded-none !rounded-t-lg shrink tabs tabs-boxed">
<button class="btn btn-sm" on:click=increment_gen>
<RefreshSvg/>
</button>
</div>
</div>
<div class="grow">
<TabCard>
<Outlet/>
</TabCard>
</div>
</div>
}
}
#[component(transparent)]
pub fn SettingsRoutes() -> impl IntoView {
view! {
<Route path="/settings" view=SettingsPage>
<Route path="/backend" view=BackendSettingsPage/>
<Route path="/model" view=ModelSettingsPage/>
</Route>
}
}

View file

@ -0,0 +1,81 @@
use std::time::Duration;
use leptos::*;
use serde::{Deserialize, Serialize};
use crate::{
api::{process_status, ProcessStatus, StartProcess, StopProcess},
app::components::FormControl,
};
/// A form component to start and stop the process.
#[component]
pub fn ProcessForm() -> impl IntoView {
let gen =
use_context::<RwSignal<super::RefreshGen>>().expect("to have found the setter provided");
let _ = gloo_timers::callback::Interval::new(1000, move || {
gen.update(|gen| *gen = crate::app::RefreshGen(gen.0 + 1));
})
.forget();
let status = create_local_resource(gen, |_| async move {
process_status().await.unwrap_or(ProcessStatus::Finished)
});
let is_running = move || match status.get().unwrap_or(ProcessStatus::Finished) {
ProcessStatus::WaitingForStart => true,
ProcessStatus::Running => true,
ProcessStatus::WaitingForStop => false,
ProcessStatus::Finished => false,
ProcessStatus::Failed => false,
};
let toggle_color = move || match status.get().unwrap_or(ProcessStatus::Finished) {
ProcessStatus::WaitingForStart => "toggle-info",
ProcessStatus::Running => "toggle-success",
ProcessStatus::WaitingForStop => "toggle-warning",
ProcessStatus::Finished => "toggle-info",
ProcessStatus::Failed => "toggle-error",
};
let stop_process_action = create_server_action::<StopProcess>();
let start_process_action = create_server_action::<StartProcess>();
let on_toggle = move |_| {
if is_running() {
stop_process_action.dispatch(StopProcess {});
} else {
start_process_action.dispatch(StartProcess {});
}
gen.update(|gen| *gen = crate::app::RefreshGen(gen.0 + 1));
};
let status_text = move || {
if let Some(status) = status.get() {
match status {
ProcessStatus::WaitingForStart => "waiting to start",
ProcessStatus::Running => "running",
ProcessStatus::WaitingForStop => "waiting to stop",
ProcessStatus::Finished => "finished",
ProcessStatus::Failed => "failed",
}
} else {
"Loading"
}
};
view! {
<FormControl label="Running">
<input
type="checkbox"
checked=is_running
on:click=on_toggle
class=move || format!("toggle {}", toggle_color())
/>
</FormControl>
<FormControl label="Status">
<span class="label-text">{status_text}</span>
</FormControl>
}
}

45
llama_forge_rs/src/lib.rs Normal file
View file

@ -0,0 +1,45 @@
#![feature(ascii_char)]
#![feature(ascii_char_variants)]
#![feature(async_closure)]
#![feature(exit_status_error)]
#![feature(rustc_private)]
#![feature(fn_traits)]
#![recursion_limit = "1024"]
// TODO Remove pre 0.1 release, its just very annoying when prototyping and moving alot of stuff
#![allow(dead_code)]
#![allow(unused_imports)]
pub mod api;
pub mod app;
#[cfg(feature = "ssr")]
pub mod server;
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use cfg_if::cfg_if;
use tracing::Level;
use tracing_wasm::WASMLayerConfigBuilder;
use crate::app::*;
console_error_panic_hook::set_once();
cfg_if! {
if #[cfg(debug_assertions)] {
let conf = WASMLayerConfigBuilder::new()
.set_max_level(Level::DEBUG)
.build();
} else {
let conf = WASMLayerConfigBuilder::new()
.set_max_level(Level::INFO)
.build();
}
}
tracing_wasm::set_as_global_default_with_config(conf);
tracing::debug!("Hello, world!");
let body = leptos::leptos_dom::document()
.body()
.expect("body element to exist");
leptos::mount_to(body, App)
}

118
llama_forge_rs/src/main.rs Normal file
View file

@ -0,0 +1,118 @@
#![feature(rustc_private)]
#![feature(fn_traits)]
#[cfg(feature = "ssr")]
fn setup_tracing() {
use tracing::level_filters::LevelFilter;
use tracing_subscriber::EnvFilter;
cfg_if::cfg_if! {
if #[cfg(debug_assertions)] {
let env_filter = EnvFilter::builder()
.with_default_directive(LevelFilter::TRACE.into())
// .parse_lossy("debug,llama_forge_rs=debug");
.parse_lossy("info,llama_forge_rs=debug");
} else {
let env_filter = EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.parse_lossy("warn,llama_forge_rs=info");
}
}
tracing_subscriber::fmt()
.pretty()
.with_env_filter(env_filter)
.init();
}
#[cfg(feature = "ssr")]
fn wry_main() -> wry::Result<()> {
use tao::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoopBuilder},
platform::unix::EventLoopBuilderExtUnix,
window::WindowBuilder,
};
use wry::WebViewBuilder;
tracing::debug!("Hello from wry main");
let event_loop = EventLoopBuilder::new().with_any_thread(true).build();
let window = WindowBuilder::new()
.with_min_inner_size(tao::dpi::LogicalSize::new(800, 600))
.with_title("Llama Forge RS")
.build(&event_loop)
.unwrap();
let builder = {
use tao::platform::unix::WindowExtUnix;
use wry::WebViewBuilderExtUnix;
let vbox = window.default_vbox().unwrap();
WebViewBuilder::new_gtk(vbox)
};
let _webview = builder.with_url("http://localhost:3000/chat").build()?;
event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;
if let Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} = event
{
*control_flow = ControlFlow::Exit
}
});
}
#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() -> anyhow::Result<()> {
use std::future::IntoFuture;
use leptos::*;
use llama_forge_rs::server::app;
use tracing;
setup_tracing();
tracing::debug!("Hello from async_main");
let conf = get_configuration(None).await.unwrap();
// TODO Add figment + app Config struct and convert into leptos /tokio conf
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
// TODO Pass through endpoint ip address of conf to llama.cpp & make llama.cpp port configurable
tracing::info!(
"[MOP] listening on http://{} :{} (app) :{} (llama.cpp)",
&addr.ip(),
&addr.port(),
8080
);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
let serve = axum::serve(listener, app(leptos_options).await.into_make_service()).into_future();
let backend_fut = async move { Ok::<(), anyhow::Error>(()) };
let (serve_res, backend_res, wry_res) = tokio::try_join!(
tokio::spawn(serve),
tokio::task::spawn_blocking(wry_main),
tokio::spawn(backend_fut),
)?;
serve_res?;
backend_res?;
wry_res?;
Ok(())
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for a purely client-side app
// see lib.rs for hydration function instead
}

View file

@ -0,0 +1,139 @@
use async_trait::async_trait;
use futures::StreamExt;
use reqwest::Client;
use reqwest_eventsource::{Event, EventSource};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use uuid::Uuid;
use super::ChatService;
use crate::api::{ChannelMessage, Chat, ChatMessage};
#[derive(Serialize, Debug)]
struct LlamaChatCompletionRequest {
stream: bool,
model: String,
messages: Vec<LlamaChatMessage>,
}
impl From<Chat> for LlamaChatCompletionRequest {
fn from(value: Chat) -> Self {
Self {
stream: true,
model: "default".to_string(),
messages: value.history.into_iter().map(|e| e.into()).collect(),
}
}
}
#[derive(Serialize, Debug)]
struct LlamaChatMessage {
role: String,
content: String,
}
impl From<ChatMessage> for LlamaChatMessage {
fn from(chat_message: ChatMessage) -> Self {
Self {
role: chat_message.role.into(),
content: chat_message.content,
}
}
}
#[derive(Deserialize, Debug)]
struct LlamaChatDelta {
content: Option<String>,
}
#[derive(Deserialize, Debug)]
struct LlamaChatChoice {
finish_reason: Option<String>,
index: i64,
delta: Option<LlamaChatDelta>,
}
#[derive(Deserialize, Debug)]
struct LlamaChatResponse {
id: String,
created: i64, // TODO Make DateTime (from unix)
model: String,
choices: Vec<LlamaChatChoice>,
object: String,
}
pub struct LlamaService {
id: Uuid,
}
impl LlamaService {
pub fn new(id: Uuid) -> Self {
Self {
id,
}
}
}
#[tracing::instrument(level = "debug")]
async fn do_chat_request(chat: Chat, sender: mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
let client = Client::new();
let request_body: LlamaChatCompletionRequest = chat.into();
let request_builder = client
.post("http://localhost:8080/v1/chat/completions")
.header("Content-Type", "application/json")
.json(&request_body);
let mut es = EventSource::new(request_builder)?;
while let Some(event) = es.next().await {
match event {
Ok(Event::Open) => tracing::debug!("Connection Open!"),
Ok(Event::Message(event)) => match event.event.as_str() {
"message" => {
let data = event.data;
let response: LlamaChatResponse = serde_json::from_str(&data).unwrap();
for choice in response.choices.into_iter() {
if let Some(delta) = choice.delta {
let content = delta.content;
if let Some(content_str) = content {
let mut string = content_str.clone();
tracing::debug!("STRING: {}", string);
if string == "\n" {
string = "<br>".to_string()
}
let msg = ChannelMessage::Token(string);
tracing::debug!(?msg);
sender.send(msg.clone()).await.expect("sender fail");
}
}
}
}
_ => {
todo! {}
}
},
Err(err) => {
tracing::debug!("Error: {}", err);
sender
.send(ChannelMessage::Stop)
.await
.expect("channel fail");
// sender.send("STOP".to_string()).await.expect("sender fail");
es.close();
}
}
}
Ok(())
}
#[async_trait]
impl ChatService for LlamaService {
#[tracing::instrument(level = "debug", skip(self))]
async fn chat_request(self, history: Vec<ChatMessage>, rx: mpsc::Sender<ChannelMessage>) {
let chat = Chat::new(self.id, history, "".to_string());
do_chat_request(chat, rx).await.expect("chat reqest error");
}
}

View file

@ -0,0 +1,145 @@
use std::{io, io::Write};
use futures::StreamExt;
use reqwest::Client;
use reqwest_eventsource::{Event, EventSource};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct CompletionRequest {
stream: bool,
n_predict: i32,
temperature: f32,
stop: Vec<String>,
repeat_last_n: i32,
repeat_penalty: f32,
top_k: i32,
top_p: f32,
min_p: f32,
tfs_z: f32,
typical_p: f32,
presence_penalty: f32,
frequency_penalty: f32,
mirostat: f32,
mirostat_tau: f32,
mirostat_eta: f32,
grammar: String,
n_probs: i32,
image_data: Vec<String>,
ignore_eos: bool,
cache_prompt: bool,
api_key: String,
slot_id: i32,
prompt: String,
}
impl Default for CompletionRequest {
fn default() -> Self {
CompletionRequest {
stream: true,
n_predict: 2048,
temperature: 0.7,
stop: vec![
"<|im_end|>".to_string(),
"<dummy00001>".to_string(),
"</s>".to_string(),
"Llama:".to_string(),
"User:".to_string(),
],
repeat_last_n: 64,
repeat_penalty: 1.1,
top_k: 40,
top_p: 0.95,
min_p: 0.05,
tfs_z: 1.0,
typical_p: 1.0,
presence_penalty: 0.0,
frequency_penalty: 0.0,
mirostat: 0.0,
mirostat_tau: 5.0,
mirostat_eta: 0.1,
grammar: "".to_string(),
n_probs: 0,
ignore_eos: false,
image_data: vec![],
cache_prompt: true,
api_key: "".to_string(),
slot_id: -1,
prompt: concat!(
"<|im_start|>system\n",
"You are a helpful assistant.",
"<|im_end|>\n",
"<|im_start|>user\n",
"What is quantum entanglement ?",
"<|im_end|>\n",
"<|im_start|>assistant\n"
)
.to_string(),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
struct CompletionResponse {
id_slot: i64,
content: String,
stop: bool,
multimodal: Option<bool>,
// Only in stop response at stream end
// TODO Add all fields
model: Option<String>, // Path to model
tokens_predicted: Option<i64>,
tokens_evaluated: Option<i64>,
tokens_cached: Option<i64>,
timings: Option<CompletionTimings>,
}
#[derive(Debug, Serialize, Deserialize)]
struct CompletionTimings {
prompt_n: i64,
prompt_ms: f64,
prompt_per_token_ms: f64,
prompt_per_second: f64,
predicted_n: i64,
predicted_ms: f64,
predicted_per_token_ms: f64,
predicted_per_second: f64,
}
pub async fn do_completion_request() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new();
let request_body = CompletionRequest::default();
let request_builder = client
.post("http://localhost:8080/completion")
.header("Accept", "text/event-stream")
.header("Content-Type", "application/json")
.header("User-Agent", "llama_forge_rs")
.json(&request_body);
let mut es = EventSource::new(request_builder)?;
while let Some(event) = es.next().await {
match event {
Ok(Event::Open) => tracing::debug!("Connection Open!"),
Ok(Event::Message(event)) => match event.event.as_str() {
"message" => {
let data = event.data;
let response: CompletionResponse = serde_json::from_str(&data).unwrap();
print!("{}", response.content);
io::stdout().flush().unwrap();
}
_ => {
todo! {}
}
},
Err(err) => {
tracing::debug!("Error: {}", err);
es.close();
}
}
}
Ok(())
}

View file

@ -0,0 +1,226 @@
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use crate::api::{ChannelMessage, ChatMessage};
pub mod llama_chat;
pub mod llama_completion;
pub mod runner;
// struct SamplerSettings {
// temp: i64,
// top_k: i64,
// top_p: i64,
// // ...
// }
#[async_trait]
pub trait ChatService: Sized {
async fn chat_request(self, history: Vec<ChatMessage>, rx: mpsc::Sender<ChannelMessage>);
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub enum BackendServiceStatus {
Started,
Stopped,
}
use std::sync::Arc;
use sysinfo::{Signal, System};
use tokio::{sync::Mutex, task::JoinHandle};
use super::backends::runner::{Runner, RunnerArgs};
fn kill_child_procs(child_str: &'static str) {
let mut system = System::new();
system.refresh_processes();
let current_pid = sysinfo::get_current_pid().unwrap();
let current_process = system.process(current_pid).unwrap();
terminate_child_processes(child_str, &system, current_process);
}
fn collect_ape_child_processes(
child_str: &'static str,
system: &System,
pid: sysinfo::Pid,
) -> Vec<sysinfo::Pid> {
let mut child_pids = Vec::new();
for process in system.processes().values() {
if let Some(parent_pid) = process.parent() {
if process.name().contains(child_str) && is_ancestor(system, parent_pid, pid) {
tracing::debug!(msg = "Found process to kill", ?process);
child_pids.push(process.pid());
}
}
}
child_pids.sort();
child_pids.reverse();
child_pids
}
fn is_ancestor(system: &System, pid: sysinfo::Pid, ancestor_pid: sysinfo::Pid) -> bool {
if pid == ancestor_pid {
return true;
}
if let Some(process) = system.process(pid) {
if let Some(parent_pid) = process.parent() {
return is_ancestor(system, parent_pid, ancestor_pid);
}
}
false
}
fn terminate_child_processes(child_str: &'static str, system: &System, process: &sysinfo::Process) {
let child_pids = collect_ape_child_processes(child_str, system, process.pid());
for child_pid in child_pids {
if let Some(child_process) = system.process(child_pid) {
// terminate_child_processes(system, child_process);
if let Some(res) = child_process.kill_with(Signal::Term) {
tracing::debug!(
"Sent SIGTERM to child process with PID: {} {}",
child_pid,
res
);
} else {
tracing::debug!(
"Failed to send SIGTERM to child process with PID: {}",
child_pid
);
}
}
}
}
#[derive(Debug, Clone)]
pub struct BackendService {
status: Arc<Mutex<BackendServiceStatus>>,
task_handle: Arc<Mutex<Option<JoinHandle<anyhow::Result<()>>>>>,
}
impl Default for BackendService {
fn default() -> Self {
Self::new()
}
}
impl BackendService {
pub fn new() -> Self {
Self {
status: Arc::new(Mutex::new(BackendServiceStatus::Stopped)),
task_handle: Arc::new(Mutex::new(None)),
}
}
#[tracing::instrument(level = "debug")]
pub async fn start(&self) -> anyhow::Result<()> {
let mut status = self.status.clone().lock_owned().await;
let mut task_handle = self.task_handle.clone().lock_owned().await;
if task_handle.is_none() && *status == BackendServiceStatus::Stopped {
let args = RunnerArgs::new(
4096,
9999,
// "./models/phi-3-mini-4k-instruct-imat-Q8_0.gguf".to_string(),
"./models/meta-llama-3-8b-instruct-imat-IQ3_XXS.gguf".to_string(),
);
let starter_fut = Runner::new_llama_server_bin(args).run();
*task_handle = Some(tokio::task::spawn(starter_fut));
*status = BackendServiceStatus::Started;
}
Ok(())
}
#[tracing::instrument(level = "debug")]
pub async fn stop(&self) -> anyhow::Result<()> {
let mut status = self.status.clone().lock_owned().await;
let mut task_handle = self.task_handle.clone().lock_owned().await;
if task_handle.is_some() && *status == BackendServiceStatus::Started {
tracing::warn!(msg = "Aborting Process", ?task_handle);
task_handle.as_mut().unwrap().abort();
// FIXME
// this is an ugly workaround as we are starting llamafile in a bash shell which somehow does not propagate systerm correctly
// we should probably keep track of our child process pids and selectively kill stuff
tracing::warn!(msg = "Killing Childs", ?task_handle);
kill_child_procs(".ape-");
kill_child_procs("llama-server");
*task_handle = None;
*status = BackendServiceStatus::Stopped;
}
Ok(())
}
pub async fn status(&self) -> BackendServiceStatus {
self.status.lock().await.clone()
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use tokio::{sync::mpsc, time::sleep};
use uuid::Uuid;
use crate::{
api::{ChannelMessage, ChatMessage, ChatRole},
server::backends::{
llama_chat::LlamaService,
BackendService,
BackendServiceStatus,
ChatService,
},
};
#[tracing_test::traced_test]
#[tokio::test]
async fn it_can_be_started_then_queried_and_then_stopped() {
let service_handle = BackendService::new();
assert_eq!(service_handle.status().await, BackendServiceStatus::Stopped);
service_handle.start().await;
assert_eq!(service_handle.status().await, BackendServiceStatus::Started);
let history = vec![
ChatMessage::new(
ChatRole::System,
"You are an helpful AI-based assistant.".to_string(),
),
ChatMessage::new(ChatRole::User, "What is 2+2 ?".to_string()),
];
let (tx, mut rx) = mpsc::channel::<ChannelMessage>(1);
let llama_service = LlamaService::new(Uuid::now_v7());
sleep(Duration::from_secs(30)).await;
let chat_req = llama_service.chat_request(history, tx);
tokio::task::spawn(chat_req);
sleep(Duration::from_millis(1000)).await;
let mut response = String::new();
while let Some(msg) = rx.recv().await {
if let ChannelMessage::Token(token) = msg {
response.push_str(token.as_str());
}
}
tracing::debug!("response: {}", response);
assert!(response.contains('4'));
service_handle.stop().await;
assert_eq!(service_handle.status().await, BackendServiceStatus::Stopped);
}
}

View file

@ -0,0 +1,93 @@
use std::ffi::OsStr;
use serde::{Deserialize, Serialize};
use tokio::process::Command;
pub struct RunnerArgs {
ctx_size: i64,
gpu_layers: i64,
model_path: String,
}
impl RunnerArgs {
pub fn new(ctx_size: i64, gpu_layers: i64, model_path: String) -> Self {
Self {
ctx_size,
gpu_layers,
model_path,
}
}
}
impl From<RunnerArgs> for Vec<String> {
fn from(value: RunnerArgs) -> Self {
vec![
"--n-gpu-layers".to_string(),
value.gpu_layers.to_string(),
"--ctx-size".to_string(),
value.ctx_size.to_string(),
// "--host".to_string(),
// "0.0.0.0".to_string(),
"-m".to_string(),
value.model_path,
]
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Runner {
pwd: Option<String>,
cmd: String,
args: Vec<String>,
}
impl Runner {
// FIXME does not exit properly when it is killed
pub fn new_llamafile_bin(runner_args: RunnerArgs) -> Self {
Self {
pwd: None,
cmd: "bash".to_string(),
args: vec![
format!(
"{}/llamafile",
std::env::current_dir().unwrap().to_string_lossy()
)
.as_str(),
"--nobrowser",
]
.into_iter()
.map(|str| str.to_string())
.chain(Into::<Vec<String>>::into(runner_args))
.collect(),
}
}
pub fn new_llama_server_bin(runner_args: RunnerArgs) -> Self {
Self {
pwd: None,
cmd: "llama-server".to_string(),
args: runner_args.into(),
}
}
#[tracing::instrument(level = "debug")]
pub async fn run(self) -> anyhow::Result<()> {
let test = OsStr::new(self.cmd.as_str());
let pwd = self
.pwd
.unwrap_or(std::env::current_dir()?.to_string_lossy().to_string());
tracing::debug!(cmd=?test, ?pwd);
let mut handle = Command::new(test)
.env("HSA_OVERRIDE_GFX_VERSION", "11.0.0")
.args(self.args.clone())
.current_dir(pwd)
.kill_on_drop(true)
.spawn()?;
handle.wait().await?.exit_ok()?;
Ok(())
}
}

View file

@ -0,0 +1,56 @@
use axum::{
body::Body,
extract::State,
http::{header, Request, Response, StatusCode, Uri},
response::{IntoResponse, Response as AxumResponse},
};
use leptos::{provide_context, view};
use rust_embed::RustEmbed;
use crate::{app::App, server::AppState};
#[derive(RustEmbed)]
#[folder = "target/site"]
struct SiteAsset;
pub struct StaticFile<T>(pub T);
impl<T> IntoResponse for StaticFile<T>
where
T: Into<String>,
{
fn into_response(self) -> Response<Body> {
let path = self.0.into();
match SiteAsset::get(path.as_str()) {
Some(content) => {
let mime = mime_guess::from_path(path).first_or_octet_stream();
([(header::CONTENT_TYPE, mime.as_ref())], content.data).into_response()
}
None => (StatusCode::NOT_FOUND, "404 Not Found").into_response(),
}
}
}
pub async fn file_and_error_handler(
uri: Uri,
State(app_state): State<AppState>,
req: Request<Body>,
) -> AxumResponse {
let path = uri.path().trim_start_matches('/').to_string();
let embed_res = StaticFile(path.clone()).into_response();
if embed_res.status().is_success() {
tracing::debug!(msg = "Found asset", ?path);
embed_res
} else {
tracing::debug!(msg = "No Asset Found, Forwarding to leptos", ?path);
let handler = leptos_axum::render_app_to_stream_with_context(
app_state.leptos_options.to_owned(),
move || {
provide_context(app_state.pool.clone());
},
move || view! { <App/> },
);
handler(req).await.into_response()
}
}

View file

@ -0,0 +1,85 @@
use std::{
future::Future,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use axum::{body::Body, http::Request};
use pin_project_lite::pin_project;
use tower::{Layer, Service};
use tracing::Span;
use uuid::Uuid; // Make sure to include `uuid` crate in your Cargo.toml
#[derive(Debug, Clone, Default)]
pub struct LoggingLayer;
impl<S> Layer<S> for LoggingLayer {
type Service = LoggingService<S>;
fn layer(&self, inner: S) -> Self::Service {
LoggingService {
inner,
}
}
}
#[derive(Clone, Debug)]
pub struct LoggingService<T> {
inner: T,
}
impl<T> Service<Request<Body>> for LoggingService<T>
where
T: Service<Request<Body>>,
{
type Error = T::Error;
type Future = LoggingServiceFuture<T::Future>;
type Response = T::Response;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
let request_uuid = Uuid::now_v7(); // Generate UUID v7
let span =
tracing::debug_span!("request", ?request_uuid, method=?req.method(), uri=?req.uri());
tracing::debug!(msg = "request started", uuid=?request_uuid);
LoggingServiceFuture {
inner: self.inner.call(req),
uuid: Arc::new(request_uuid), // Store UUID in an Arc for shared ownership
span: Arc::new(span),
}
}
}
pin_project! {
#[derive(Clone, Debug)]
pub struct LoggingServiceFuture<T> {
#[pin]
inner: T,
uuid: Arc<Uuid>, // Shared state between LoggingService and LoggingServiceFuture
span: Arc<Span>,
}
}
impl<T> Future for LoggingServiceFuture<T>
where
T: Future,
{
type Output = T::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
match this.inner.poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(output) => {
tracing::debug!(msg = "request finished", uuid=?this.uuid);
Poll::Ready(output)
}
}
}
}

View file

@ -0,0 +1,167 @@
use std::str::FromStr;
use axum::{
body::Body,
extract::{DefaultBodyLimit, FromRef, Path, State},
http::Request,
response::IntoResponse,
routing::get,
Extension,
Router,
};
use leptos::*;
use leptos_axum::{generate_route_list, handle_server_fns_with_context, LeptosRoutes};
use leptos_router::RouteListing;
use sqlx::{
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
ConnectOptions,
SqlitePool,
};
use tower::Layer;
use tower_http::{
compression::CompressionLayer,
trace::{
DefaultMakeSpan,
DefaultOnEos,
DefaultOnFailure,
DefaultOnRequest,
DefaultOnResponse,
TraceLayer,
},
CompressionLevel,
};
use tracing::Level;
use self::fileserv::file_and_error_handler;
use crate::{
api::run_starter_task,
app::*,
server::middleware::{LoggingLayer, LoggingService},
};
pub mod backends;
mod fileserv;
mod middleware;
pub fn pool() -> Result<SqlitePool, ServerFnError> {
use_context::<SqlitePool>().ok_or_else(|| ServerFnError::ServerError("Pool missing.".into()))
}
#[derive(FromRef, Debug, Clone)]
pub struct AppState {
pub leptos_options: LeptosOptions,
pub pool: SqlitePool,
pub routes: Vec<RouteListing>,
}
pub async fn server_fn_handler(
State(app_state): State<AppState>,
path: Path<String>,
request: Request<Body>,
) -> impl IntoResponse {
tracing::debug!("handling server_fn {:?}", path);
handle_server_fns_with_context(
move || {
provide_context(app_state.pool.clone());
},
request,
)
.await
}
pub async fn leptos_routes_handler(
State(app_state): State<AppState>,
req: Request<Body>,
) -> impl IntoResponse {
tracing::debug!("handling leptos_route: {:?}", req);
let handler = leptos_axum::render_route_with_context(
app_state.leptos_options.clone(),
app_state.routes.clone(),
move || {
provide_context(app_state.pool.clone());
},
App,
);
let response = handler(req).await;
tracing::debug!("leptos_route response: {:?}", response);
response
}
pub async fn app(leptos_options: LeptosOptions) -> Router {
async fn new_pool() -> Result<SqlitePool, Box<dyn std::error::Error>> {
// TODO Save this in xdg_config_dir /data dir
let db_options = SqliteConnectOptions::from_str("sqlite:db.sqlite3")?
.create_if_missing(true)
.optimize_on_close(true, None)
.journal_mode(SqliteJournalMode::Wal)
.synchronous(SqliteSynchronous::Normal)
.disable_statement_logging()
.busy_timeout(std::time::Duration::from_secs(16))
.statement_cache_capacity(512)
.to_owned();
tracing::debug!(
msg = "Connectiong to db",
conn_str = ?db_options.to_url_lossy()
);
let pool = SqlitePoolOptions::new().connect_with(db_options).await?;
sqlx::migrate!()
.run(&pool)
.await
.expect("could not run SQLx migrations");
Ok(pool)
}
let routes = generate_route_list(App);
let pool = new_pool().await.expect("pool err");
// TODO move this out of server(pool has to be moved out too)
let task = run_starter_task(pool.clone());
tokio::task::spawn(task);
let app_state = AppState {
leptos_options,
// stream_registry: Arc::default(),
pool: pool.clone(),
routes: routes.clone(),
};
const MAX_BODY_LIMIT: usize = 16 * 1024 * 1024; // 16 MB
tracing::debug!("routes: {:?}", routes);
// build our application with a route
Router::new()
.route(
"/api/*fn_name",
get(server_fn_handler).post(server_fn_handler),
)
.leptos_routes_with_handler(routes, get(leptos_routes_handler))
.fallback(file_and_error_handler)
.with_state(app_state)
.layer(Extension(pool))
.layer(
// Todo Readd gzip & deflate and add compress_when which skips them if response is a stream
CompressionLayer::new()
.no_gzip()
.no_deflate()
.quality(CompressionLevel::Fastest),
)
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().include_headers(true))
.on_request(DefaultOnRequest::new().level(Level::INFO))
.on_response(DefaultOnResponse::new().level(Level::INFO))
.on_eos(DefaultOnEos::new().level(Level::DEBUG))
.on_failure(DefaultOnFailure::new().level(Level::ERROR)),
)
.layer(DefaultBodyLimit::max(MAX_BODY_LIMIT))
.layer(LoggingLayer)
}

View file

@ -0,0 +1,9 @@
<svg class="looka-1j8o68f" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
<path d="m94.04 198.39-75.58-44a11.96 12.06 0 0 1-5.96-10.41V56.03a11.96 12.06 0 0 1 5.96-10.46L94.04 1.62a11.96 12.06 0 0 1 11.96 0l75.54 43.99a11.96 12.06 0 0 1 5.96 10.45v87.92a11.96 12.06 0 0 1-5.96 10.45L106 198.4a11.96 12.06 0 0 1-11.96 0z" fill="#fd7014"/>
<g fill="#222831">
<path d="M88.98 76.07H91v-6.15c0-2.26-1.82-4.1-4.06-4.1h-6.1v2.05h2.6a4.08 4.08 0 0 0 3.5 6.15 4 4 0 0 0 2.03-.57zm-2.03-4.1c-1.13 0-2.04-.92-2.04-2.05s.91-2.05 2.04-2.05 2.03.92 2.03 2.05-.91 2.05-2.03 2.05zm18.32 3.07c0-3.07-3.29-3.07-5.11-3.07s-5.11 0-5.11 3.07c0 2.37.6 4.13 5.1 4.13s5.12-1.76 5.12-4.13zm-8.19 0c0-.66.46-1.02 3.08-1.02s3.07.36 3.07 1.02c0 .93.6 2.08-3.07 2.08s-3.08-1.15-3.08-2.08zm3.08 6.16c-4.68 0-11.18 5.15-11.18 10.24 0 4.82 4.6 7.2 11.18 7.2s11.18-2.38 11.18-7.2c0-5.09-6.5-10.25-11.18-10.25zm7.99 7c-.62.74-2.08 2.21-3.93 2.21-1.9 0-2.77-.95-3.05-1.32v-5.74c2.45.48 5.39 2.5 6.98 4.85zm-9-4.85v5.74c-.29.38-1.16 1.32-3.06 1.32-1.85 0-3.3-1.48-3.92-2.21 1.59-2.35 4.52-4.37 6.97-4.85zm1 13.24c-4.4 0-9.14-.93-9.14-5.15 0-.42.08-.84.2-1.27 1.01 1.02 2.7 2.29 4.88 2.29a5.8 5.8 0 0 0 4.07-1.47 5.8 5.8 0 0 0 4.06 1.47c2.18 0 3.87-1.27 4.89-2.29.12.43.2.85.2 1.27 0 4.22-4.75 5.15-9.15 5.15z"/>
<path d="M120.24 56.57c2.23-2.15 5.33-5.9 5.33-10.2 0-6.4-2.12-9.66-2.2-9.8l-.48-.71-.79.35c-6.32 2.83-9.84 8.38-11.55 11.98-3.01-1.21-6.5-1.83-10.4-1.83s-7.37.62-10.39 1.83c-1.7-3.6-5.23-9.15-11.55-11.98l-.78-.35-.48.71c-.09.14-2.2 3.4-2.2 9.8 0 4.3 3.1 8.05 5.33 10.2-2.78 4.8-2.3 10.12-2.3 13.35 0 16-2.1 24.88-3.01 29.51l2 .4c.93-4.72 3.03-13.74 3.03-29.9 0-4.05-.14-11.59 5.53-16.65l.42-.37-.09-.55c-.73-4.7-2.84-9.09-4.57-12.05 3.9 3.01 6.14 7.11 7.23 9.63l.41.95.94-.43a25 25 0 0 1 10.49-2.05c4 0 7.53.69 10.48 2.05l.94.43.42-.95c1.08-2.52 3.32-6.62 7.22-9.63-1.73 2.96-3.84 7.34-4.57 12.05l-.08.55.41.37c5.67 5.06 5.53 12.6 5.53 16.64 0 16.17 2.1 25.2 3.04 29.91l2-.4c-.92-4.63-3-13.5-3-29.5 0-3.24.47-8.55-2.31-13.36zm-39.02-1.74c-1.95-1.93-4.44-5.06-4.44-8.47 0-3.4.66-5.8 1.19-7.2 1.57 2.37 4.6 7.46 5.6 12.98-.9.85-1.67 1.75-2.35 2.69zm41.13-15.67c.53 1.4 1.18 3.8 1.18 7.2 0 3.4-2.49 6.54-4.43 8.47a19.19 19.19 0 0 0-2.35-2.7c1-5.5 4.02-10.6 5.6-12.97z"/>
<path d="M109.3 69.92v6.15h2.04v-2.62a4 4 0 0 0 2.03.57 4.09 4.09 0 0 0 3.5-6.15h2.6v-2.04h-6.1a4.09 4.09 0 0 0-4.07 4.1zm6.1 0c0 1.13-.9 2.05-2.03 2.05s-2.03-.92-2.03-2.05.9-2.05 2.03-2.05 2.03.92 2.03 2.05z"/>
</g>
<path d="M69.19 112.8v1.38h-4.76v-7.17h1.6v5.79zm5.78 0v1.38h-4.75v-7.17h1.6v5.79zm5.79 1.38q-.11-.37-.25-.76t-.27-.79h-2.78l-.27.79q-.14.39-.25.76h-1.66l.76-2.14q.36-.99.7-1.85t.68-1.65.7-1.53h1.52q.35.75.69 1.53t.68 1.65.7 1.85.76 2.14zm-1.92-5.54-.15.42-.24.62-.3.78-.32.89h2.03l-.32-.9q-.15-.42-.3-.77t-.24-.62-.16-.42zm6.45-1.63q.18.34.42.85t.5 1.08.53 1.2.48 1.15l.48-1.15.52-1.2q.26-.59.5-1.08t.43-.85h1.46q.1.72.19 1.6t.15 1.84.12 1.92.1 1.81h-1.56l-.08-2.27q-.05-1.23-.16-2.49l-.4.97-.45 1.05-.43 1.01-.35.82h-1.12l-.35-.82-.42-1-.45-1.06-.41-.97q-.1 1.26-.15 2.49t-.09 2.27H83.2l.1-1.8.12-1.93q.06-.96.16-1.84t.19-1.6zm12.08 7.17q-.11-.37-.25-.76t-.27-.79h-2.77l-.28.79q-.14.39-.25.76H91.9l.76-2.14q.36-.99.7-1.85t.68-1.65.7-1.53h1.52l.7 1.53q.34.78.67 1.65t.7 1.85.77 2.14zm-1.92-5.54-.15.42-.24.62-.3.78-.31.89h2.02l-.32-.9q-.15-.42-.3-.77t-.23-.62-.17-.42zm7.02 5.54v-7.17h4.77v1.36h-3.16v1.5h2.81v1.35h-2.81v2.96zm7.24-3.59q0 .53.13.96t.37.73.6.47.8.16q.43 0 .79-.16t.6-.47.36-.73.13-.96-.13-.95-.37-.74-.6-.47-.79-.16q-.45 0-.8.17t-.59.47-.37.74-.13.94zm5.43 0q0 .92-.27 1.62t-.74 1.17-1.13.71-1.4.24q-.73 0-1.37-.24t-1.13-.7-.76-1.18-.28-1.62.29-1.62.77-1.17 1.13-.71 1.35-.24q.73 0 1.38.24t1.13.7.76 1.18.27 1.62zm3.42-3.66q1.6 0 2.46.57t.85 1.79q0 .76-.34 1.23t-1 .74q.22.27.46.61t.46.73.45.78.4.8h-1.8l-.4-.7-.4-.71q-.2-.35-.42-.65t-.4-.55h-.8v2.61h-1.6v-7.06q.52-.1 1.08-.15t1-.04zm.1 1.38h-.32q-.14 0-.26.03v1.94h.45q.9 0 1.3-.22t.39-.78q0-.53-.4-.75t-1.16-.22zm8.14-.06q-1.12 0-1.62.63t-.5 1.71q0 .53.13.96t.37.74.61.48.86.17h.46q.2 0 .33-.05v-2.5h1.6v3.56q-.28.11-.92.24t-1.57.13q-.8 0-1.45-.25t-1.12-.72-.7-1.17-.26-1.59q0-.9.28-1.59t.76-1.17 1.13-.73 1.4-.25q.5 0 .9.06t.7.16.48.18.27.15l-.46 1.29q-.33-.18-.75-.3t-.93-.14zm3.74 5.93v-7.17h4.8v1.36h-3.2v1.4h2.84v1.33h-2.84v1.73h3.44v1.35zm-53.31 4.29q9.83 0 15.06 3.53t5.23 10.95q0 4.64-2.11 7.53t-6.08 4.54q1.32 1.65 2.77 3.78t2.87 4.45 2.74 4.82 2.45 4.93H89.14l-2.43-4.39q-1.23-2.23-2.52-4.32t-2.55-3.97-2.52-3.4h-4.85V163h-9.83v-43.4q3.2-.63 6.64-.88t6.15-.26zm.56 8.45q-1.07 0-1.92.06t-1.6.13v11.94h2.77q5.54 0 7.94-1.4t2.4-4.76q0-3.24-2.43-4.6t-7.16-1.37zm40.59 28.52q2.08 0 3.43-.35t2.17-.95 1.14-1.43.31-1.85q0-2.15-2.01-3.58t-6.93-3.08q-2.15-.77-4.29-1.75t-3.84-2.48-2.78-3.62-1.07-5.18 1.14-5.49 3.21-4.16 5.04-2.64 6.68-.92q4.41 0 7.63.96t5.29 2.1l-2.84 7.8q-1.82-.95-4.06-1.68t-5.39-.73q-3.53 0-5.07.99t-1.54 3.01q0 1.2.56 2.03t1.6 1.5 2.4 1.2 3 1.12q3.4 1.27 5.92 2.5t4.2 2.9 2.48 3.87.82 5.4q0 6.16-4.29 9.56t-12.91 3.4q-2.9 0-5.23-.35t-4.13-.86-3.09-1.08-2.17-1.08l2.77-7.88q1.95 1.08 4.82 1.94t7.03.86z" fill="#393939"/>
</svg>

After

Width:  |  Height:  |  Size: 5 KiB

View file

@ -0,0 +1 @@
@use 'tailwind'

View file

@ -0,0 +1,14 @@
@config "../tailwind.config.js";
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
.debug-border {
@apply border border-rose-500;
}
}
leptos-island {
display: contents;
}

View file

@ -0,0 +1,35 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./**/**.rs",
"./public/*.html",
],
safelist: [
"backdrop-blur-sm",
],
theme: {
extend: {
animation: {
'bounce-twice': 'bounce 1s 1.5',
},
width: {
'128': '32rem',
'192': '48rem',
'256': '64rem',
}
},
},
darkMode: 'class',
plugins: [require("@tailwindcss/typography"), require("daisyui")],
daisyui: {
// fd7014 (logo color)
themes: ["halloween"], // false: only light + dark | true: all themes | array: specific themes like this ["light", "dark", "cupcake"]
darkTheme: "halloween", // name of one of the included themes for dark mode
base: true, // applies background color and foreground color for root element by default
styled: true, // include daisyUI colors and design decisions for all components
utils: true, // adds responsive and modifier utility classes
prefix: "", // prefix for daisyUI classnames (components, modifiers and responsive class names. Not colors)
logs: false,
themeRoot: ":root", // The element that receives theme color CSS variables
},
}

1507
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

13
package.json Normal file
View file

@ -0,0 +1,13 @@
{
"name": "oeko-mono",
"description": "",
"version": "0.1.1",
"author": "Tristan Druyen <tristan@vault81.mozmail.com>",
"license": "AGPL",
"devDependencies": {
"@tailwindcss/forms": "0.5.7",
"@tailwindcss/typography": "0.5.10",
"daisyui": "4.7.3",
"tailwindcss": "3.4.1"
}
}

16
rust-toolchain.toml Normal file
View file

@ -0,0 +1,16 @@
[toolchain]
channel = "nightly-2024-07-15"
targets = [
"x86_64-unknown-linux-gnu",
"wasm32-unknown-unknown",
"x86_64-pc-windows-msvc",
]
components = [
"cargo",
"rustfmt",
"rust-analyzer",
"rust-src",
"rustc-codegen-cranelift",
"rustc-dev",
]
profile = "default"