#!/usr/bin/env bash
# 组合包安装脚本（Trove 自动生成，勿手改；组合包文档为准）
# combo: combo-local-llm-finetune ｜ 本地大模型微调/推理环境（ollama + open-webui + LLaMA-Factory） ｜ 状态: verified
# 生成: 2026-09-24 ｜ 详情: https://trove.xin/combos/combo-local-llm-finetune.html ｜ 依赖警告见文档
# 按官方下载源 + 国内镜像适配；每条命令后可验证（预期输出见组合包文档）。
set -euo pipefail

# ==== [1/4] ollama：模型下载与运行底座 ====
# 版本要求: >= 0.33.2（2026-08-29 最新 v0.33.2；旧版本 < 0.30 的 API/模型兼容性差，建议直接最新）
# Linux（官方脚本；国内 GitHub 直连慢时改用下方手动路径）
curl -fsSL https://gh-proxy.com/https://github.com/ollama/ollama/releases/latest/download/install.sh | sh
# 或手动：下载 tar.zst 解压（需 tar --zstd 或 zstd 工具）
curl -sL -o /tmp/ollama.tar.zst https://gh-proxy.com/https://github.com/ollama/ollama/releases/latest/download/ollama-linux-amd64.tar.zst
mkdir -p /tmp/ollama-bin && tar --zstd -xf /tmp/ollama.tar.zst -C /tmp/ollama-bin
/tmp/ollama-bin/bin/ollama --version   # 预期输出: ollama version 0.33.2

# ==== [2/4] open-webui：网页界面 ====
# 版本要求: >= 0.11.1（Docker tag 建议 `:main` 跟随最新；pip 形态硬性要求 Python 3.11~3.12，实测 3.14 装不上）
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway \
    -v open-webui:/app/backend/data --name open-webui --restart always \
    -e ENABLE_SIGNUP=true \
    -e RAG_EMBEDDING_ENGINE=ollama \
    -e RAG_EMBEDDING_MODEL=nomic-embed-text \
    ghcr.nju.edu.cn/open-webui/open-webui:main
# 国内镜像：直接写 ghcr.nju.edu.cn（2026-08-30 实测拉取成功，镜像 7.16GB）；官方 ghcr.io 慢时同前缀替换

# ==== [3/4] LLaMA-Factory：本地微调工具 ====
# 版本要求: >= 0.9.5（Python >= 3.10；需 PyTorch 2.x，CUDA 版需先装对应 torch 轮子）
pip install llamafactory --index-url https://pypi.tuna.tsinghua.edu.cn/simple
llamafactory-cli version   # 预期输出: LLaMA Factory 版本号（2026-08-30 实测 0.9.5）

# ==== [4/4] nomic-embed-text：知识库 embedding ====
# 版本要求: latest（2026-08-30 实测 v0.32.x 配套正常）
ollama pull nomic-embed-text   # 274MB，官方 registry（实测约 45s）
curl -s localhost:11434/api/embed -d '{"model":"nomic-embed-text","input":["测试"]}'   # 预期输出: 768 维向量

