Uncategorized

VMware Intelligent Assist on Your Own Server – Ollama, Snowflake Embeddings and Caddy on Ubuntu (GPU or CPU)

Can VMware Intelligent Assist run on a model that lives on one Ubuntu server, with or without a GPU, and never sends a prompt outside the building?

That was the question I wanted to answer in my VCF 9.1.1 lab.

The answer is yes. VCF Operations offers two LLM provider types: Google Gemini and VCF Private AI. The second one accepts any OpenAI-compatible endpoint, as long as that endpoint has a DNS name, serves HTTPS and checks a bearer token.

The current release adds one more piece to the picture. Next to the chat model, Intelligent Assist uses an embedding model, Snowflake/snowflake-arctic-embed-m-v2.0, to pick the right skill for every question. So our server has to offer both models, behind one address.

In this article, we will build exactly that on Ubuntu 24.04. We will run a chat model with Ollama, serve the Snowflake model next to it, join both behind a small proxy, put Caddy in front of everything for TLS and the token, connect it to VCF Operations as a VCF Private AI provider and finally cut the server off from the Internet.

There are two ways through the guide:

  • GPU path – an NVIDIA card passed through to the VM. This is what I run in my lab and what I recommend.
  • CPU path – no GPU at all. Good enough to see the whole chain working, but much slower.

Both paths share almost every step. Where they differ, the step says so.

This is deliberately written as a from-zero, command-by-command lab guide. Every step ends with a Checkpoint: do not move on until the result matches.

What makes this lab interesting?

The whole AI backend is one Linux VM and four small services. No Kubernetes, no Harbor, no Supervisor. The model still answers questions about the real infrastructure, because VCF Operations runs its own tools and only asks the model what to call and how to summarise the result.

Important: this is not a supported Broadcom configuration. Treat it as a lab pattern.

Before We Start: What Are We Actually Building?

There are six layers involved:

  1. GPU layer (GPU path only) – an NVIDIA card with its driver inside the Ubuntu VM.
  2. Chat model layer – Ollama runs qwen3:4b-instruct on 127.0.0.1:11434.
  3. Embedding layer – a small Python service runs the Snowflake model on 127.0.0.1:11436.
  4. Proxy layer – a small Python proxy on 127.0.0.1:11435 presents both models as one endpoint.
  5. Gateway layer – Caddy terminates TLS for a DNS name, checks the bearer token and forwards the request to the proxy.
  6. Consumer layer – VCF Operations treats the gateway as a VCF Private AI provider, and VMware Intelligent Assist uses both models.

Figure 1. Architecture – one VM, four services, only port 443 reachable from the network.

The final request path looks like this:

User
 |
 v
VMware Intelligent Assist
 |
 v
VCF Operations agent / tools
 |
 v
VCF Private AI LLM Provider
 |
 v
https://<llm-fqdn>        (Caddy, 443/tcp, bearer token)
 |
 v
127.0.0.1:11435           (proxy: one model list, routing)
 |                    \
 v                     v
127.0.0.1:11434        127.0.0.1:11436
(Ollama, chat)         (Snowflake, embeddings)
 |
 v
NVIDIA GPU or CPU

Why is the gateway needed at all?

VCF Operations is strict about the endpoint. It refuses a URL with an IP address, always sends Authorization: Bearer <token> and reads the model list from GET /v1/models. Ollama speaks the API, but it has no TLS, no DNS name and no authentication. Caddy adds all three without touching the models.

And why a proxy between Caddy and Ollama?

Because VCF Operations reads one model list from one address, and Ollama does not serve the Snowflake model. The proxy takes Ollama’s list, adds Snowflake to it and sends every embedding request to the right service. It also smooths out one detail: some Intelligent Assist tools come without a parameter schema, which Ollama rejects, so the proxy adds an empty one on the way through.

The Lab Configuration

Before copying commands, here is the complete working configuration so that the values used later make sense.

ComponentWorking lab value
VCF9.1.1
VCF Operations extensionsAdvanced Configuration, VMware Intelligent Assist
Operating systemUbuntu 24.04 LTS VM, GPU attached with Dynamic DirectPath I/O
GPUNVIDIA Tesla V100 PCIe, 32 GB
Chat modelqwen3:4b-instruct, served as qwen3:4b-instruct-32k
Parallel requests in Ollama4
Embedding modelSnowflake/snowflake-arctic-embed-m-v2.0, on CPU
Embedding stacksentence-transformers 5.x, transformers 4.x, PyTorch CPU build
GatewayCaddy 2.x on 443/tcp
Certificateself-signed, 10 years, issued for <llm-fqdn>
Internet accessthrough a corporate HTTP proxy, during installation only

Do not treat these values as universal sizing.

What is reusable is the pattern and the order of the steps. The numbers that really matter come from how VCF Operations calls the model, described at the end of the article: many requests at once, prompts of up to about 21,000 tokens, and about 60 seconds for each call.

Throughout the article I use four placeholders. Replace them with your own values:

PlaceholderMeaning
<llm-fqdn>DNS name of the Ubuntu server
<llm-ip>IP address of the Ubuntu server
<proxy-host>:<port>your HTTP proxy, only if the server reaches the Internet through one
<vcf-ops-ip>IP address of the VCF Operations appliance (one per node in a cluster)

Which Path Should You Choose?

On the GPU path, the card’s memory decides how many requests Ollama can work on at the same time. Every parallel slot keeps its own 32k context, about 4.7 GB for this model, on top of about 2.5 GB for the model itself. In my lab, 4 slots use 22 GB of the V100.

GPU memoryOLLAMA_NUM_PARALLELVRAM used (approx.)
16 GB212 GB
20 GB317 GB
24 GB or more422 GB

What about the CPU path?

It works, with one honest limitation. A CPU reads a long prompt much more slowly than a GPU, and some Intelligent Assist skills send prompts of about 21,000 tokens. Simple questions such as Show me your skills come back fine; skills with long instructions can run past the 60-second limit. Use the CPU path to learn the setup, and the GPU path for daily work.

GPU pathCPU path
vCPU816 or more
RAM32 GB48 GB
Disk100 GB100 GB
OLLAMA_NUM_PARALLEL2–4, from the table above1

The Snowflake model runs on the CPU on both paths. It is small, a short text takes about 0.03 seconds, and keeping it off the card leaves all of the GPU memory to the chat model.

Prerequisites

I assume that the VCF side already exists. Before we begin, verify that you have:

  • a healthy VCF 9.1.1 deployment with VCF Operations,
  • Log Management deployed (it is a prerequisite for the AI services),
  • a local VCF Operations admin account, or a role with the Extensions permission,
  • an Ubuntu 24.04 VM with a static IP address, sized for your path,
  • for the GPU path, an ESXi host with a supported NVIDIA GPU (Part 0 attaches it to the VM),
  • the ability to create a DNS A record that VCF Operations can resolve,
  • network access from VCF Operations to the server on 443/tcp,
  • temporary Internet access from the server, directly or through a proxy, for packages and models.

If all of those are in place, we can start.

Part 0 – Pass the GPU Through to the Ubuntu VM (GPU Path Only)

On the CPU path, skip straight to Part 1.

The model runs inside a regular VM, so the first thing we need is not Linux at all. We need to give that VM the whole physical GPU.

Step 0 – Enable Dynamic DirectPath I/O and Attach the GPU

  1. Open the vSphere Client and go to Hosts and Clusters.
  2. Select the ESXi host that contains the NVIDIA card and open Configure > Hardware > PCI Devices.
  3. Locate the NVIDIA GPU (vendor ID 0x10DE) and enable Passthrough. Reboot the host if vSphere asks for it and wait until it is Connected again.
  4. Edit the Ubuntu VM while it is powered off. Under VM Options > Boot Options, use EFI firmware with Secure Boot disabled (Step 3 explains why).
  5. Under Virtual Hardware > Memory, select Reserve all guest memory (All locked). Passthrough devices require the full memory reservation.
  6. Click Add New Device > PCI Device and select the NVIDIA GPU in Dynamic DirectPath I/O mode. No vGPU profile is used.
  7. Power on the VM.

Checkpoint: the VM powers on and, inside the guest, lspci | grep -i nvidia lists the card.

What if the VM does not power on, or the driver cannot use the card?

GPUs with large memory windows need a 64-bit MMIO space in the VM. With the VM powered off, add these two advanced parameters under VM Options > Advanced > Edit Configuration and power it on again:

pciPassthru.use64bitMMIO = TRUE
pciPassthru.64bitMMIOSizeGB = 64

Why passthrough and not vGPU?

Because one model on one card does not need sharing. Passthrough gives the VM the whole GPU memory with no vGPU licensing or host driver. The trade-off is that the VM is pinned to its host: no vMotion while the GPU is attached.

Part 1 – Prepare Ubuntu

Step 1 – Configure the Proxy (Only If You Use One)

Skip this step if the server reaches the Internet directly.

In a corporate network, apt, pip and your shell need the proxy, but local traffic must never go through it. Without the no_proxy exception, even a request to 127.0.0.1 is sent to the proxy and comes back as an HTML error page.

printf 'Acquire::http::Proxy "http://<proxy-host>:<port>";\nAcquire::https::Proxy "http://<proxy-host>:<port>";\n' | sudo tee /etc/apt/apt.conf.d/95proxy

export PROXY="http://<proxy-host>:<port>"
export http_proxy="$PROXY" https_proxy="$PROXY" HTTP_PROXY="$PROXY" HTTPS_PROXY="$PROXY"
export no_proxy="localhost,127.0.0.1" NO_PROXY="localhost,127.0.0.1"

Checkpoint: curl -s -o /dev/null -w '%{http_code}\n' https://ollama.com prints 200.

Remember that export only affects the current shell. If you open a new session during the installation, run the three export lines again. Services such as Ollama do not inherit them either; we will deal with that in Part 3.

Why sudo -E in the commands below?

Because sudo drops your environment by default, proxy included. -E keeps it, so pip and the other downloads run as root still find the way out.

Step 2 – Update the System and Install the Tools

sudo apt update && sudo apt -y upgrade
sudo apt -y install curl jq openssl zstd pciutils mokutil python3-venv

Reboot if the upgrade installed a new kernel:

sudo reboot

Checkpoint: jq --version and python3 -m venv --help both answer without errors.

Part 2 – Install the NVIDIA Driver (GPU Path Only)

On the CPU path, skip straight to Part 3.

Step 3 – Confirm the GPU and Secure Boot State

lspci | grep -i nvidia
mokutil --sb-state

The first command must list your card. If it prints nothing, go back to Part 0.

The second matters because the driver is built as a kernel module. With Secure Boot enabled, the module will not load until you enrol a MOK key. For a lab, disable Secure Boot in the VM settings.

Checkpoint: the GPU is visible and Secure Boot is reported as disabled.

Step 4 – Install the Recommended Driver

sudo apt -y install ubuntu-drivers-common
sudo ubuntu-drivers devices
sudo ubuntu-drivers install
sudo reboot

Which driver will Ubuntu pick?

ubuntu-drivers devices lists the packages for your card and marks one as recommended. For Turing and newer cards (T4, A100, L40S, RTX 4000 Ada) the recommended package is fine. For older data-centre cards such as a Tesla P40 or V100, make sure the chosen package is a proprietary one, not an -open one: the open kernel modules only support Turing and newer. If needed, install the proprietary package from the list by name, for example sudo apt -y install nvidia-driver-580-server.

Step 5 – Verify the Driver

nvidia-smi

Checkpoint: the table shows your GPU, the driver version and the full memory size (32768 MiB on my V100). A message saying the GPU is not supported by open nvidia.ko means an open driver on a pre-Turing card: remove it and install the proprietary package from Step 4.

Part 3 – Run the Chat Model with Ollama

Step 6 – Install Ollama

curl -fsSL https://ollama.com/install.sh | sh

The installer creates an ollama user and a systemd service, and detects the GPU.

Checkpoint: on the GPU path, the last lines include NVIDIA GPU installed. On the CPU path, the installer reports that Ollama will run in CPU-only mode, which is exactly what we want there.

Step 7 – Configure the Ollama Service

Three settings matter for VCF Operations:

  • Listen on localhost only. Nothing outside the server should reach Ollama directly; the proxy and Caddy will be the only way in.
  • Never unload the model. By default Ollama unloads an idle model after a few minutes. The next question then waits for the model to load, and VCF Operations may give up.
  • Work on several requests at once. One question in Intelligent Assist fires a burst of model calls at the same time. With one slot, they queue up until the last ones hit the 60-second limit.

GPU path (take the number from the table in Which Path Should You Choose?):

sudo mkdir -p /etc/systemd/system/ollama.service.d
sudo tee /etc/systemd/system/ollama.service.d/override.conf > /dev/null <<'EOF'
[Service]
Environment="OLLAMA_HOST=127.0.0.1:11434"
Environment="OLLAMA_KEEP_ALIVE=-1"
Environment="OLLAMA_NUM_PARALLEL=4"
EOF

CPU path (parallel slots only split the same cores, so we keep one):

sudo mkdir -p /etc/systemd/system/ollama.service.d
sudo tee /etc/systemd/system/ollama.service.d/override.conf > /dev/null <<'EOF'
[Service]
Environment="OLLAMA_HOST=127.0.0.1:11434"
Environment="OLLAMA_KEEP_ALIVE=-1"
Environment="OLLAMA_NUM_PARALLEL=1"
EOF

If you use a proxy, the service needs its own copy of the settings. This is the most common reason for ollama pull failing with i/o timeout even though curl works in your shell:

sudo tee /etc/systemd/system/ollama.service.d/proxy.conf > /dev/null <<'EOF'
[Service]
Environment="HTTPS_PROXY=http://<proxy-host>:<port>"
Environment="HTTP_PROXY=http://<proxy-host>:<port>"
Environment="NO_PROXY=localhost,127.0.0.1"
EOF

Apply the changes:

sudo systemctl daemon-reload
sudo systemctl restart ollama
systemctl show ollama --property=Environment

Checkpoint: the output contains OLLAMA_HOST=127.0.0.1:11434, OLLAMA_KEEP_ALIVE=-1, your OLLAMA_NUM_PARALLEL and, if configured, the proxy variables.

Step 8 – Pull the Model and Create a 32k Variant

This is one of the most important details in the whole build.

Intelligent Assist sends each skill’s instructions and tool definitions with every request. For the larger skills, such as the inventory queries, that is about 21,000 tokens before the user’s question is even added. Ollama’s default context is far smaller, so we create a variant of the model with a 32k context:

ollama pull qwen3:4b-instruct
cat > ~/qwen3-4b-32k.Modelfile <<'EOF'
FROM qwen3:4b-instruct
PARAMETER num_ctx 32768
EOF
ollama create qwen3:4b-instruct-32k -f ~/qwen3-4b-32k.Modelfile
ollama list

Why a small instruct model and not a bigger “thinking” one?

Because VCF Operations waits about 60 seconds for each model call, and one question means many calls. Reasoning models spend that time thinking before they answer and run out of time. A 4B instruct model answers quickly, still picks the right tool and is the safe starting point.

Step 9 – Verify the Model

ollama run qwen3:4b-instruct-32k "Explain VMware vSphere in one sentence."
ollama ps
curl -s http://127.0.0.1:11434/v1/models | jq '.data[].id'

Checkpoint:

  • the model answers with a sensible sentence,
  • ollama ps shows context 32768, Forever in the UNTIL column and, on the GPU path, 100% GPU,
  • the API lists qwen3:4b-instruct-32k.

If ollama ps shows a CPU/GPU split on the GPU path, the model and its slots do not fit in the card: lower OLLAMA_NUM_PARALLEL in Step 7. If jq reports a parse error, your shell is sending local traffic to the proxy; check no_proxy from Step 1.

Part 4 – Serve the Snowflake Embedding Model

Ollama now answers chat requests. The second model, Snowflake, needs a small service of its own. It is a short Python program built on sentence-transformers that speaks the same OpenAI API as Ollama; the full code is in Appendix A.

Step 10 – Create the Service Account and the Python Environment

sudo useradd --system --home-dir /var/lib/vcf-embed --shell /usr/sbin/nologin vcfembed
sudo mkdir -p /opt/vcf-embed
sudo python3 -m venv /opt/vcf-embed/venv
sudo -E /opt/vcf-embed/venv/bin/pip install torch --index-url https://download.pytorch.org/whl/cpu
sudo -E /opt/vcf-embed/venv/bin/pip install "transformers>=4.51,<5" "sentence-transformers>=5,<6" fastapi uvicorn

Checkpoint: both installs end with Successfully installed .... The first one takes a few minutes.

Why the version limits?

Because the Snowflake model ships its own model code, and that code does not work with transformers 5.x. The model loads, but the first embedding fails with an IndexError. Pinning transformers to 4.x, and sentence-transformers to the matching 5.x line, avoids it.

Step 11 – Add the Program

Open the editor, paste the whole of embed_server.py from Appendix A, save with Ctrl+O, Enter and leave with Ctrl+X:

sudo nano /opt/vcf-embed/embed_server.py

Then make the folder readable for the service account and check the file:

sudo chmod -R a+rX /opt/vcf-embed
sudo /opt/vcf-embed/venv/bin/python -m py_compile /opt/vcf-embed/embed_server.py && echo "embed_server.py OK"

Checkpoint: embed_server.py OK.

Do not skip the chmod. On hardened systems, files created with sudo are readable by root only, and the service then fails to start with status=203.

Step 12 – Download the Model and Test It

We download the model (about 1.2 GB) as the service account itself, so that it lands where the service will look for it:

sudo systemd-run --pipe --wait --collect \
  -p User=vcfembed -p StateDirectory=vcf-embed \
  -p Environment=HF_HOME=/var/lib/vcf-embed \
  -p Environment=HTTPS_PROXY=$PROXY -p Environment=HTTP_PROXY=$PROXY \
  /opt/vcf-embed/venv/bin/python -c "
from sentence_transformers import SentenceTransformer as S
m = S('Snowflake/snowflake-arctic-embed-m-v2.0', trust_remote_code=True,
      config_kwargs={'use_memory_efficient_attention': False, 'unpad_inputs': False})
v = m.encode(['test VCF'], normalize_embeddings=True)
print('OK, dimension:', v.shape[1])
"

Checkpoint: after the download, OK, dimension: 768. Warnings about HF_TOKEN, rope_scaling or double-check … malicious code are expected and harmless.

What is config_kwargs doing there?

By default, the Snowflake model asks for xformers, a library that only works on a GPU. The two options switch that feature off. The vectors are the same, and embed_server.py does the same thing on its own.

Step 13 – Run It as a Service

The service starts in offline mode, so from now on it never tries to reach the Internet:

sudo tee /etc/systemd/system/vcf-embed.service > /dev/null <<'EOF'
[Unit]
Description=VCF embeddings - Snowflake arctic-embed-m-v2.0
After=network.target

[Service]
User=vcfembed
Group=vcfembed
StateDirectory=vcf-embed
WorkingDirectory=/opt/vcf-embed
Environment=HF_HOME=/var/lib/vcf-embed
Environment=HF_HUB_OFFLINE=1
Environment=TRANSFORMERS_OFFLINE=1
Environment=EMBED_DEVICE=cpu
ExecStart=/opt/vcf-embed/venv/bin/uvicorn embed_server:app --host 127.0.0.1 --port 11436
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now vcf-embed
sleep 20
systemctl is-active vcf-embed
curl -s http://127.0.0.1:11436/health; echo
curl -s http://127.0.0.1:11436/v1/embeddings \
  -H "Content-Type: application/json" \
  -d '{"model":"Snowflake/snowflake-arctic-embed-m-v2.0","input":"test VCF"}' \
  | jq '.data[0].embedding | length'

Checkpoint: active, then a line with "status":"ok" and "dimension":768, then 768.

Part 5 – Join Both Models Behind One Proxy

We now have two services on two ports. VCF Operations needs one. The proxy from Appendix B sits on 127.0.0.1:11435 and does three things:

  • answers GET /v1/models with Ollama’s list plus the Snowflake model,
  • sends embedding requests for Snowflake to port 11436, and everything else to Ollama,
  • adds an empty parameter schema to tools that come without one, because Ollama rejects those requests with error 400.

Step 14 – Install the Proxy

sudo mkdir -p /opt/vcf-proxy
sudo python3 -m venv /opt/vcf-proxy/venv
sudo -E /opt/vcf-proxy/venv/bin/pip install fastapi uvicorn httpx
sudo nano /opt/vcf-proxy/app.py

Paste the whole of app.py from Appendix B, save and leave the editor. Then:

sudo chmod -R a+rX /opt/vcf-proxy
sudo /opt/vcf-proxy/venv/bin/python -m py_compile /opt/vcf-proxy/app.py && echo "app.py OK"

Checkpoint: app.py OK.

Step 15 – Run the Proxy as a Service

EMBED_ROUTES tells the proxy which model lives where. DUMP_DIR is where it saves any request Ollama still rejects, so you can see exactly what VCF Operations sent.

sudo tee /etc/vcf-proxy.env > /dev/null <<'EOF'
OLLAMA_URL=http://127.0.0.1:11434
EMBED_ROUTES=Snowflake/snowflake-arctic-embed-m-v2.0=http://127.0.0.1:11436
EOF
sudo tee /etc/systemd/system/vcf-proxy.service > /dev/null <<'EOF'
[Unit]
Description=VCF proxy - Ollama + Snowflake embeddings
After=network.target ollama.service vcf-embed.service

[Service]
EnvironmentFile=/etc/vcf-proxy.env
Environment=DUMP_DIR=/var/lib/vcf-proxy/dump
WorkingDirectory=/opt/vcf-proxy
ExecStart=/opt/vcf-proxy/venv/bin/uvicorn app:app --host 127.0.0.1 --port 11435
DynamicUser=yes
StateDirectory=vcf-proxy
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now vcf-proxy
sleep 3
systemctl is-active vcf-proxy
curl -s http://127.0.0.1:11435/v1/models | jq -r '.data[].id'
curl -s http://127.0.0.1:11435/v1/embeddings \
  -H "Content-Type: application/json" \
  -d '{"model":"Snowflake/snowflake-arctic-embed-m-v2.0","input":"test"}' \
  | jq '.data[0].embedding | length'

Checkpoint: active; a model list with qwen3:4b-instruct-32k, qwen3:4b-instruct and Snowflake/snowflake-arctic-embed-m-v2.0; then 768.

Part 6 – Give the Server a Name and a Token

Step 16 – Generate the Bearer Token

The token is a shared secret between VCF Operations and the gateway. It is generated once and stored in two places: the Caddy configuration and the provider definition in VCF Operations.

openssl rand -hex 32 > ~/llm-token.txt
chmod 600 ~/llm-token.txt
cat ~/llm-token.txt

Checkpoint: a 64-character hexadecimal string. Store it in your password manager.

Step 17 – Create the DNS Record

VCF Operations refuses an endpoint given as an IP address. Create an A record in the DNS that VCF Operations uses:

<llm-fqdn>  ->  <llm-ip>

If the server already has a name in DNS, you can use it. Then set the values for the rest of the session and add the name to the proxy exceptions:

export LLM_FQDN=<llm-fqdn>
export LLM_IP=<llm-ip>
export no_proxy="localhost,127.0.0.1,${LLM_FQDN}" NO_PROXY="localhost,127.0.0.1,${LLM_FQDN}"
nslookup $LLM_FQDN

Checkpoint: nslookup returns the server’s IP address. Ideally, check it from a machine in the VCF management network as well.

Part 7 – Put Caddy in Front of Everything

Step 18 – Install Caddy

On Ubuntu, Caddy comes from the project’s official repository:

sudo apt -y install debian-archive-keyring apt-transport-https gnupg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt -y install caddy
caddy version

Checkpoint: caddy version prints a 2.x version. If apt says debian-archive-keyring has no installation candidate, drop it from the first line: it is a Debian package, and Ubuntu does not need it.

Step 19 – Create a Long-Lived Certificate

VCF Operations shows the certificate thumbprint once and asks you to accept it. If the certificate changes later, the provider stops working until you accept it again. That rules out Caddy’s built-in internal CA, whose leaf certificates rotate every 12 hours. We create one self-signed certificate for ten years instead:

sudo mkdir -p /etc/caddy/certs /var/log/caddy
sudo openssl req -x509 -newkey rsa:2048 -nodes -days 3650 \
  -subj "/CN=${LLM_FQDN}" \
  -addext "subjectAltName=DNS:${LLM_FQDN},IP:${LLM_IP}" \
  -addext "extendedKeyUsage=serverAuth" \
  -keyout /etc/caddy/certs/llm.key -out /etc/caddy/certs/llm.crt
sudo chown -R caddy:caddy /etc/caddy/certs /var/log/caddy
sudo chmod 600 /etc/caddy/certs/llm.key
openssl x509 -in /etc/caddy/certs/llm.crt -noout -fingerprint -sha256

Checkpoint: note the SHA-256 fingerprint. You will compare it in VCF Operations in Part 9.

Step 20 – Write the Caddyfile

The configuration below serves HTTPS for your DNS name, forwards requests with the correct token to the proxy, answers everything else with 401, and logs every request as JSON. The first command writes the file with two placeholders, the second replaces them with your name and token.

sudo tee /etc/caddy/Caddyfile > /dev/null <<'EOF'
{
    admin off
    auto_https disable_redirects
}

https://FQDN_HERE:443 {
    tls /etc/caddy/certs/llm.crt /etc/caddy/certs/llm.key

    # only requests carrying the shared token reach the models
    @authorized header Authorization "Bearer TOKEN_HERE"

    handle @authorized {
        reverse_proxy 127.0.0.1:11435 {
            header_up Host 127.0.0.1:11435
            header_up -Authorization
            flush_interval -1
            transport http {
                dial_timeout 10s
                response_header_timeout 15m
                read_timeout 15m
                write_timeout 15m
            }
        }
    }

    # everything else is rejected before it touches the models
    handle {
        header WWW-Authenticate "Bearer"
        respond "Unauthorized" 401
    }

    log {
        output file /var/log/caddy/access.log {
            roll_size 10MiB
            roll_keep 5
        }
        format json
    }
}
EOF
sudo sed -i "s/FQDN_HERE/${LLM_FQDN}/g; s/TOKEN_HERE/$(cat ~/llm-token.txt)/g" /etc/caddy/Caddyfile
sudo chown root:caddy /etc/caddy/Caddyfile
sudo chmod 640 /etc/caddy/Caddyfile
sudo -u caddy caddy validate --config /etc/caddy/Caddyfile
sudo systemctl enable caddy
sudo systemctl restart caddy
systemctl status caddy --no-pager

A few details that are easy to miss:

  • header_up -Authorization strips the token before forwarding, so it never leaves the gateway.
  • flush_interval -1 streams the answer token by token instead of buffering it.
  • The long transport timeouts make sure Caddy never cuts a slow model; the only time limit left is the one in VCF Operations.
  • The Caddyfile contains the token, hence 640 and group caddy.
  • validate runs as the caddy user. Run as root, it would create the log file owned by root, and the service would then fail with permission denied.
  • Because of admin off, always use systemctl restart caddy, never reload.

Checkpoint: Valid configuration and active (running).

Step 21 – Open the Firewall for VCF Operations Only

Ubuntu ships with ufw switched off. If sudo ufw status shows Status: inactive, there is nothing to do here; restrict access on your network firewall instead.

If ufw is active, allow 443/tcp only from the VCF Operations appliance. Ports 11434, 11435 and 11436 listen on 127.0.0.1 and stay unreachable anyway.

sudo ufw allow from <vcf-ops-ip> to any port 443 proto tcp
sudo ufw status numbered

If VCF Operations runs as a multi-node cluster, add one rule per node.

Checkpoint: the rule is listed, and sudo ss -tlnp | grep -E '1143[456]' shows the three internal services on 127.0.0.1 only.

Part 8 – Test It the Way VCF Operations Will

This is an important troubleshooting habit: first prove that the gateway and both models work on their own. Only then add VCF Operations.

Step 22 – Run the Four Gateway Tests

The tests below replay what VCF Operations does: list the models without a token, list them with a token, ask for an embedding and send a chat request that offers one tool.

export LLM_TOKEN=$(cat ~/llm-token.txt)
CURL="curl -s --resolve ${LLM_FQDN}:443:127.0.0.1 --cacert /etc/caddy/certs/llm.crt"

# Test 1: no token -> expect 401
$CURL -o /dev/null -w '%{http_code}\n' https://${LLM_FQDN}/v1/models

# Test 2: valid token -> expect both chat models and Snowflake
$CURL -H "Authorization: Bearer ${LLM_TOKEN}" https://${LLM_FQDN}/v1/models | jq '.data[].id'

# Test 3: embedding -> expect 768
$CURL -H "Authorization: Bearer ${LLM_TOKEN}" -H "Content-Type: application/json" \
  https://${LLM_FQDN}/v1/embeddings \
  -d '{"model":"Snowflake/snowflake-arctic-embed-m-v2.0","input":"test"}' | jq '.data[0].embedding | length'

# Test 4: one tool offered -> expect finish_reason "tool_calls"
$CURL -H "Authorization: Bearer ${LLM_TOKEN}" -H "Content-Type: application/json" \
  https://${LLM_FQDN}/v1/chat/completions -d '{
  "model": "qwen3:4b-instruct-32k",
  "messages": [{"role": "user", "content": "What is the CPU usage of host esx-01?"}],
  "tools": [{"type": "function", "function": {
    "name": "get_host_metrics",
    "description": "Returns metrics of an ESXi host",
    "parameters": {"type": "object",
      "properties": {"host": {"type": "string"}, "metric": {"type": "string", "enum": ["cpu", "memory"]}},
      "required": ["host", "metric"]}}}]
}' | jq '.choices[0].finish_reason, .choices[0].message.tool_calls'

Checkpoint:

  • Test 1 prints 401: the gateway is guarding the models.
  • Test 2 prints qwen3:4b-instruct-32k, qwen3:4b-instruct and Snowflake/snowflake-arctic-embed-m-v2.0.
  • Test 3 prints 768.
  • Test 4 prints "tool_calls" and a call to get_host_metrics with esx-01 and cpu.

Test 4 is the one that matters most. A model that answers in prose instead of returning a tool call is useless to Intelligent Assist, however good its answer sounds.

Step 23 – Test from the VCF Management Network

From any machine on the same network path as VCF Operations:

curl -sk --noproxy '*' -o /dev/null -w '%{http_code}\n' https://<llm-fqdn>/v1/models

Checkpoint: 401. A 000 or a hang means a firewall, routing or DNS problem between VCF Operations and the server.

Part 9 – Connect VCF Operations

Step 24 – Enable the Required Components

  1. Navigate to Build > Lifecycle > VCF Management and use Add Component if Log Management is not deployed yet. Wait until it is healthy.
  2. Open Extensions > Extension Management and install Advanced Configuration and VMware Intelligent Assist. Reload the page.
  3. Open Extensions > Advanced Configuration and click Enable Services.

If the Extensions tile is missing while you are signed in through VCF SSO, use the local admin account or add the Extensions permission to your role under Operate > Administration > Control Panel > Access Control > Roles.

Step 25 – Add the Gateway as a VCF Private AI Provider

  1. Navigate to Extensions > Advanced Configuration > LLM Providers.
  2. Click Add Provider and select VCF Private AI.
  3. API Endpoint: https://<llm-fqdn> – without /v1.
  4. API Key: the token from Step 16.
  5. Click Connect, compare the thumbprint with the one from Step 19 and click Accept.
  6. Wait for the provider to report Healthy.

Why no /v1?

Because VCF Operations appends /v1/models, /v1/embeddings and /v1/chat/completions itself. With /v1 in the URL, it asks for /v1/v1/models, gets a 404 and reports that the provider endpoint is unreachable.

Step 26 – Select the Models

  1. Open Extensions > Advanced Configuration > Models.
  2. Select qwen3:4b-instruct-32k as the chat model. Pick the -32k variant, not the base model.
  3. If your build shows a separate field for the embedding model, select Snowflake/snowflake-arctic-embed-m-v2.0.

The model list is read when the provider is saved. After adding a model in Ollama, edit the provider, paste the token again and click Connect to see it. Each provider type can also be added only once, so pointing VCF Operations at another server means editing this provider, not adding a second one.

Part 10 – Prove That It Is Using Real VCF Data

A generic question like “What is VMware Cloud Foundation?” is not a good final test. Any model could answer that from its training data. Ask something that forces VCF Operations to call its own tools.

Step 27 – Watch the Gateway Log

On the server, keep a live, readable view of the access log open:

sudo tail -f /var/log/caddy/access.log | jq -r \
  '[.request.method, .request.uri, .status, "\(.duration*10|round/10)s", "\(.bytes_read)B"] | join(" ")'

Step 28 – Ask Questions That Need Live Data

In Extensions > VMware Intelligent Assist, start a new session and try:

Show me your skills
List my vCenters
Show me the ESXi hosts and their connection state
Summarize the active alerts by severity

Checkpoint: for every question, the log shows a few POST /v1/embeddings 200 lines followed by a burst of POST /v1/chat/completions 200, each well under 60 seconds, and the answers contain objects from your own inventory.

One thing to keep in mind: if you ask the model itself whether it runs locally, it will happily claim that it runs in the cloud. The model has no idea where it is executed. The proof is the gateway log, the GPU in nvidia-smi and, after Part 11, the missing Internet path.

Part 11 – Cut the Server Off from the Internet

The whole point of a local model is that no prompt and no infrastructure data leave the building. Once Part 10 works, the server no longer needs the Internet: both models are on disk and VCF Operations talks to them over the management network.

Step 29 – Remove the Proxy from Ollama, apt and the Shell

sudo rm -f /etc/systemd/system/ollama.service.d/proxy.conf
sudo systemctl daemon-reload
sudo systemctl restart ollama
sudo rm -f /etc/apt/apt.conf.d/95proxy
unset PROXY http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
grep -ri proxy /etc/environment /etc/profile.d/ /etc/apt/apt.conf.d/ 2>/dev/null
systemctl show vcf-embed --property=Environment

Checkpoint: systemctl show ollama --property=Environment contains no proxy variables, the grep prints nothing, and the embedding service shows HF_HUB_OFFLINE=1 and TRANSFORMERS_OFFLINE=1.

Step 30 – Block the Way Out

The recommended option is to ask the network team to deny this server on the proxy and on the egress firewall. Keep only what the server really needs:

  • 443/tcp in from VCF Operations,
  • SSH in from administrators,
  • DNS and NTP to internal servers,
  • directory services, if you sign in with domain accounts.

Why not simply deny all outbound traffic on the server?

Because it also cuts DNS, NTP, monitoring agents and, on domain-joined servers, your own logon. Blocking the single exit point is precise and easy to reverse.

Step 31 – Prove the Isolation

curl -s --max-time 10 -o /dev/null -w '%{http_code}\n' https://ollama.com
ollama pull qwen3:8b
ollama run qwen3:4b-instruct-32k "Reply with OK."
curl -s http://127.0.0.1:11436/health; echo

Checkpoint:

  • curl prints 000: no route to the Internet,
  • ollama pull fails: no new downloads,
  • ollama run replies and /health reports ok: both models work locally,
  • Intelligent Assist still answers, and the gateway log shows 200.

A warning in the Ollama log about model recommendations refresh failed is expected from now on: Ollama tries to reach its website and no longer can.

Living with an Isolated Server

TaskHow
New chat model or Ollama updateTemporarily restore proxy.conf from Step 7, pull, then repeat Steps 29–30
New version of the embedding librariesTemporarily restore the proxy, update the venv, run the test from Step 12 again
Ubuntu security updatesPoint apt to an internal mirror, or open a short maintenance window through the proxy
NVIDIA driver updatesKeep the proprietary branch on pre-Turing GPUs; reboot after every kernel update
Models with a :cloud suffixDo not use them: they run on external servers by design, and after isolation they fail anyway

What Happens Behind the Scenes When You Ask a Question?

This is where the design becomes interesting, and where most of the sizing decisions come from.

One question in Intelligent Assist is not one model call. VCF Operations runs a short pipeline:

  1. It turns the question into embeddings with the Snowflake model and uses them to find the matching skills.
  2. It asks the chat model to score those skills and to plan the steps.
  3. It sends the chosen skill’s instructions and tool definitions to the chat model, which answers with a tool call, for example “list vCenters”.
  4. VCF Operations runs the tool against its own inventory and metrics, sends the result back, and the model either calls another tool or writes the final answer.

Three practical consequences follow from that pipeline:

  • Every call must finish in about 60 seconds. VCF Operations closes the connection after that. The gateway log shows status 499 at 60 seconds, and the UI reports The AI provider returned an error. That is why a fast instruct model and enough parallel slots beat a slower, smarter model.
  • Many calls arrive at once. In my lab a single question produced 15 to 25 chat calls, most of them in parallel. With one slot in Ollama, they queue up and the last ones time out.
  • The context must hold the skill and the results. The larger skills send about 21,000 tokens of instructions and tools. That is why we serve the model with a 32k context, and why broad questions on a small model are better asked as narrower ones.

Troubleshooting

Almost every failure is visible in the Caddy access log, not in the VCF Operations UI. For the services themselves, use journalctl -u ollama -n 50, journalctl -u vcf-embed -n 50, journalctl -u vcf-proxy -n 50 and journalctl -u caddy -n 50. Every row below is something I actually hit while building this lab.

SymptomCauseFix
nvidia-smi: not supported by open nvidia.koOpen driver on a pre-Turing GPUInstall the proprietary package (Step 4)
nvidia-smi fails after a successful installSecure Boot blocks the driver moduleDisable Secure Boot or enrol a MOK key (Step 3)
ollama pull: i/o timeoutThe service does not know the proxyproxy.conf drop-in (Step 7)
jq: parse error on a local curlLocal request sent to the proxyAdd localhost,127.0.0.1 and the FQDN to no_proxy
Step 12 ends at once with status=203The service account cannot read /opt/vcf-embedsudo chmod -R a+rX /opt/vcf-embed (Step 11)
Step 12: AssertionError: please install xformersThe model’s GPU-only defaultKeep config_kwargs in the test (Step 12)
Step 12: IndexError in rope_cos[position_ids]transformers 5.xPin the versions from Step 10, run sudo rm -rf /var/lib/vcf-embed/modules, repeat Step 12
Caddy fails with access.log: permission deniedLog file created by rootsudo chown -R caddy:caddy /var/log/caddy and restart; validate as caddy (Step 20)
VCF: The embedding model … is not availableSnowflake missing from the model list VCF readTest 2 in Step 22 must list it; then edit the provider and Connect again
VCF: endpoint is unreachable, log shows 404 /v1/v1/models/v1 in the endpoint URLUse https://<llm-fqdn> only
VCF: endpoint is unreachable, nothing in the logDNS, firewall or routingStep 17 and Step 23
Log shows 401 from VCF OperationsToken mismatchEdit the provider and paste the token from ~/llm-token.txt
UI: The AI provider returned an error; log shows chat times climbing to 60 s, then 499Too few parallel slots for the burst of callsRaise OLLAMA_NUM_PARALLEL within your VRAM (Step 7)
Same message; log ends with 400, Ollama log says properties must be an objectA tool without a parameter schema reached Ollama directlyCaddy must point at the proxy on 11435, not at Ollama (Step 20)
Same message; Ollama log says exceeds the available context sizeThe skill’s prompt is longer than the contextUse qwen3:4b-instruct-32k (Step 8) and select it in VCF (Step 26)
A rejected request you cannot explainSomething new in what VCF Operations sendssudo ls /var/lib/private/vcf-proxy/dump/ holds the full request
Monitoring reports failed units named run-u...Earlier test runs of systemd-run without --collectsudo systemctl reset-failed 'run-u*'
An answer says found 1 and 1 more not shownA small model miscounting in a long answerNot a setup problem; ask a narrower question
VCF reports a changed certificateCertificate regeneratedKeep the 10-year certificate; if replaced, edit the provider and accept again
New model not in the listList read only when the provider is savedEdit the provider, paste the token, Connect
VM does not power on after adding the GPUMemory not fully reserved, or not enough 64-bit MMIO spaceReserve all guest memory and add the MMIO parameters (Part 0)

Rolling Back

To return to plain Ollama behind Caddy, without the Snowflake service and the proxy:

sudo systemctl disable --now vcf-proxy vcf-embed
sudo sed -i 's/127\.0\.0\.1:11435/127.0.0.1:11434/g' /etc/caddy/Caddyfile
sudo -u caddy caddy validate --config /etc/caddy/Caddyfile && sudo systemctl restart caddy

Intelligent Assist then reports the missing embedding model again, but nothing else changes. To remove everything, also run sudo apt remove caddy and sudo systemctl disable --now ollama, and delete /opt/vcf-embed, /opt/vcf-proxy and /var/lib/vcf-embed.

Final Verification Checklist

  • GPU path: nvidia-smi shows the GPU on the expected driver branch.
  • ollama ps shows context 32768, Forever and, on the GPU path, 100% GPU.
  • Ollama, the embedding service and the proxy listen on 127.0.0.1 only.
  • /health on port 11436 reports ok and dimension 768.
  • The proxy lists both chat models and Snowflake.
  • <llm-fqdn> resolves to the server from the VCF management network.
  • Caddy is active and serves the 10-year certificate.
  • No token: 401. Valid token: model list. Embedding: 768. One tool: tool_calls.
  • The VCF Private AI provider is Healthy.
  • The -32k model is selected in VCF Operations.
  • Intelligent Assist answers with live inventory, every call under 60 s.
  • The server has no Internet path, and Intelligent Assist still works.

Conclusion

We started with one Ubuntu server, with or without a GPU. We ended with VMware Intelligent Assist answering questions about the real VCF environment through two models that never leave that server.

The interesting part is how little is needed in between. Ollama already speaks the API that VCF Operations expects. A small Python service adds the Snowflake model. A small proxy makes both look like one endpoint. Caddy adds the three things VCF Operations insists on: a DNS name, TLS and a bearer token.

Everything else is about respecting the way Intelligent Assist calls the model: many calls at once, long prompts and about 60 seconds for each.

From an infrastructure perspective, it is a small and very transparent stack, where every request can be read in one log file.

From the consumer perspective, it is just another VCF Private AI provider, except that it runs on hardware you already own and keeps working with the network cable to the Internet unplugged.

Appendix A – embed_server.py

Paste into /opt/vcf-embed/embed_server.py in Step 11.

"""
embed_server.py - local, OpenAI-compatible embeddings service.

Serves Snowflake/snowflake-arctic-embed-m-v2.0 (or another Hugging Face model)
through sentence-transformers:
  POST /v1/embeddings   - OpenAI format (input: string or list; encoding_format: float or base64)
  GET  /v1/models       - a single-model list
  GET  /health          - status and vector dimension

Listens on localhost only; VCF reaches it through the proxy (app.py) and Caddy.
"""

import base64
import logging
import os
import time
from typing import List, Optional, Union

import numpy as np
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

HF_MODEL = os.getenv("EMBED_HF_MODEL", "Snowflake/snowflake-arctic-embed-m-v2.0")
SERVED_NAME = os.getenv("EMBED_SERVED_NAME", HF_MODEL)
DEVICE = os.getenv("EMBED_DEVICE", "cpu")
BATCH = int(os.getenv("EMBED_BATCH", "32"))
MAX_INPUTS = int(os.getenv("EMBED_MAX_INPUTS", "2048"))
MAX_SEQ = int(os.getenv("EMBED_MAX_SEQ_LENGTH", "8192"))

logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"), format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("embed-server")
app = FastAPI(title="embed-server")
_model = None


def _dim(model):
    # renamed in newer sentence-transformers releases
    getter = getattr(model, "get_embedding_dimension", None) or model.get_sentence_embedding_dimension
    return getter()


def get_model():
    """Loads the model on first use (or at startup, see on_startup)."""
    global _model
    if _model is None:
        from sentence_transformers import SentenceTransformer

        t0 = time.monotonic()
        # Snowflake m-v2.0 asks for xformers by default (GPU only). Turning off
        # memory-efficient attention and unpadding gives the same vectors without it.
        cfg = {}
        if os.getenv("EMBED_NO_XFORMERS", "true").lower() in ("1", "true", "yes"):
            cfg = {"use_memory_efficient_attention": False, "unpad_inputs": False}
        _model = SentenceTransformer(
            HF_MODEL, device=DEVICE, trust_remote_code=True, config_kwargs=cfg
        )
        _model.max_seq_length = min(MAX_SEQ, _model.max_seq_length or MAX_SEQ)
        log.info("model %s loaded on %s in %.1f s, dimension %s",
                 HF_MODEL, DEVICE, time.monotonic() - t0, _dim(_model))
    return _model


@app.on_event("startup")
def on_startup():
    if os.getenv("EMBED_LAZY", "false").lower() != "true":
        get_model()


class EmbeddingRequest(BaseModel):
    input: Union[str, List[str]]
    model: Optional[str] = None
    encoding_format: Optional[str] = "float"
    dimensions: Optional[int] = None
    user: Optional[str] = None


@app.post("/v1/embeddings")
def embeddings(req: EmbeddingRequest):
    texts = [req.input] if isinstance(req.input, str) else list(req.input)
    if not texts or not all(isinstance(t, str) for t in texts):
        raise HTTPException(400, "input must be a string or a list of strings")
    if len(texts) > MAX_INPUTS:
        raise HTTPException(400, f"too many inputs in one request (max {MAX_INPUTS})")

    t0 = time.monotonic()
    vecs = get_model().encode(
        texts, batch_size=BATCH, normalize_embeddings=True, convert_to_numpy=True, show_progress_bar=False
    ).astype(np.float32)
    if req.dimensions and 0 < req.dimensions < vecs.shape[1]:
        # the model supports shortened vectors (Matryoshka); re-normalize after cutting
        vecs = vecs[:, : req.dimensions]
        vecs /= np.linalg.norm(vecs, axis=1, keepdims=True) + 1e-12

    def encode(v: np.ndarray):
        if req.encoding_format == "base64":
            return base64.b64encode(v.astype("<f4").tobytes()).decode("ascii")
        return v.tolist()

    tokens = sum(len(t.split()) for t in texts)
    log.info("embeddings: %d inputs, dimension %d, %.2f s", len(texts), vecs.shape[1], time.monotonic() - t0)
    return {
        "object": "list",
        "model": SERVED_NAME,
        "data": [{"object": "embedding", "index": i, "embedding": encode(v)} for i, v in enumerate(vecs)],
        "usage": {"prompt_tokens": tokens, "total_tokens": tokens},
    }


@app.get("/v1/models")
def models():
    return {"object": "list", "data": [{"id": SERVED_NAME, "object": "model", "owned_by": "local"}]}


@app.get("/health")
def health():
    m = get_model()
    return {"status": "ok", "model": SERVED_NAME, "dimension": _dim(m), "device": DEVICE}

Appendix B – app.py

Paste into /opt/vcf-proxy/app.py in Step 14.

"""
app.py - proxy between Caddy and Ollama for the VCF Operations AI Assistant.

Flow:  VCF Operations -> Caddy (TLS + bearer token) -> this proxy -> Ollama
                                                                 +-> embeddings service (Snowflake)

What it does:
  GET  /v1/models      Ollama's model list plus the embedding models from EMBED_ROUTES,
                       so VCF finds e.g. Snowflake/snowflake-arctic-embed-m-v2.0
  POST /v1/embeddings  a model listed in EMBED_ROUTES goes to its service, others to Ollama
  POST /v1/chat/completions
                       repairs tool and response_format schemas Ollama rejects
                       (e.g. a tool with no parameters), then forwards to Ollama
  everything else      goes to Ollama unchanged, responses are streamed
"""

import json
import logging
import os
import time

import httpx
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, StreamingResponse
from starlette.background import BackgroundTask

# ---------------------------------------------------------------- configuration
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://127.0.0.1:11434").rstrip("/")

# Embedding models served outside Ollama (by embed_server.py):
#   EMBED_ROUTES=Snowflake/snowflake-arctic-embed-m-v2.0=http://127.0.0.1:11436
# Separate several models with a semicolon.
EMBED_ROUTES = {}
for _item in os.getenv("EMBED_ROUTES", "").split(";"):
    if "=" in _item:
        _name, _url = _item.rsplit("=", 1)
        if _name.strip() and _url.strip():
            EMBED_ROUTES[_name.strip()] = _url.strip().rstrip("/")

# extra fields for these models in /v1/models (JSON)
try:
    EMBED_MODEL_META = json.loads(os.getenv("EMBED_MODEL_META", '{"model_type": "EMBEDDINGS"}'))
except ValueError:
    EMBED_MODEL_META = {}

logging.basicConfig(
    level=os.getenv("LOG_LEVEL", "INFO"),
    format="%(asctime)s %(levelname)s %(message)s",
)
log = logging.getLogger("vcf-proxy")

# trust_env=False: Ollama and the embeddings service are local, never via a corporate proxy
client = httpx.AsyncClient(timeout=httpx.Timeout(900.0, connect=10.0), trust_env=False)
app = FastAPI(title="vcf-proxy")

# -------------------------------------------------------------- forwarding
_SKIP_REQ = {"host", "content-length", "connection", "accept-encoding", "transfer-encoding", "authorization"}
_SKIP_RESP = {"content-length", "transfer-encoding", "connection", "content-encoding"}


async def forward(request: Request, body: bytes, base_url: str = OLLAMA_URL):
    url = base_url + request.url.path
    if request.url.query:
        url += "?" + request.url.query
    headers = {k: v for k, v in request.headers.items() if k.lower() not in _SKIP_REQ}
    upstream = await client.send(
        client.build_request(request.method, url, headers=headers, content=body),
        stream=True,
    )
    resp_headers = {k: v for k, v in upstream.headers.items() if k.lower() not in _SKIP_RESP}
    return StreamingResponse(
        upstream.aiter_raw(),
        status_code=upstream.status_code,
        headers=resp_headers,
        background=BackgroundTask(upstream.aclose),
    )


# ------------------------------------------------- JSON schema repair
_SCHEMA_MAPS = ("properties", "patternProperties", "$defs", "definitions")
_SCHEMA_LISTS = ("anyOf", "oneOf", "allOf", "prefixItems")
_SCHEMA_ONE = ("items", "additionalProperties", "not", "if", "then", "else", "contains")


def fix_schema(schema, path: str, fixes: list):
    """Repairs a JSON schema so that Ollama's template parser accepts it."""
    if isinstance(schema, str):
        try:
            schema = json.loads(schema)
            fixes.append(f"{path}: string instead of object")
        except ValueError:
            return {"type": "string"}
    if not isinstance(schema, dict):
        return schema
    for key in _SCHEMA_MAPS:
        if key in schema:
            val = schema[key]
            if isinstance(val, str):
                try:
                    val = json.loads(val)
                except ValueError:
                    val = None
            if not isinstance(val, dict):
                fixes.append(f"{path}.{key}: {type(val).__name__} -> {{}}")
                val = {}
            schema[key] = {k: fix_schema(v, f"{path}.{key}.{k}", fixes) for k, v in val.items()}
    if schema.get("type") == "object" and "properties" not in schema:
        schema["properties"] = {}
        fixes.append(f"{path}: added empty properties")
    if "required" in schema:
        req = schema["required"]
        props = schema.get("properties")
        if not isinstance(req, list):
            fixes.append(f"{path}.required: {type(req).__name__} -> []")
            schema["required"] = []
        elif isinstance(props, dict):
            kept = [r for r in req if isinstance(r, str) and r in props]
            if len(kept) != len(req):
                fixes.append(f"{path}.required: dropped names not in properties")
                schema["required"] = kept
    for key in _SCHEMA_LISTS:
        if isinstance(schema.get(key), list):
            schema[key] = [fix_schema(v, f"{path}.{key}[{i}]", fixes) for i, v in enumerate(schema[key])]
    for key in _SCHEMA_ONE:
        if isinstance(schema.get(key), (dict, str)):
            schema[key] = fix_schema(schema[key], f"{path}.{key}", fixes)
    return schema


def fix_request(body: dict) -> list:
    fixes = []
    for i, tool in enumerate(body.get("tools") or []):
        fn = tool.get("function") if isinstance(tool, dict) else None
        if not isinstance(fn, dict):
            continue
        name = fn.get("name", i)
        params = fn.get("parameters")
        if params is None or params == [] or params == "":
            fn["parameters"] = {"type": "object", "properties": {}}
            fixes.append(f"tool {name}: no parameters")
            continue
        params = fix_schema(params, f"tool {name}", fixes)
        if not isinstance(params, dict) or params.get("type") not in (None, "object"):
            params = {"type": "object", "properties": {}}
            fixes.append(f"tool {name}: parameters is not an object")
        params.setdefault("type", "object")
        params.setdefault("properties", {})
        fn["parameters"] = params
    rf = body.get("response_format")
    if isinstance(rf, dict) and isinstance(rf.get("json_schema"), dict) and "schema" in rf["json_schema"]:
        rf["json_schema"]["schema"] = fix_schema(rf["json_schema"]["schema"], "response_format", fixes)
    return fixes


@app.post("/v1/chat/completions")
async def chat_completions(request: Request):
    raw = await request.body()
    try:
        body = json.loads(raw)
    except ValueError:
        return await forward(request, raw)
    if isinstance(body, dict):
        try:
            fixes = fix_request(body)
        except Exception as exc:  # a repair must never block a request
            log.warning("schema repair failed: %s", exc)
            fixes = []
        if fixes:
            log.info("chat: repaired %d place(s): %s", len(fixes), "; ".join(fixes[:10]))
            raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
    upstream = await forward(request, raw)
    if upstream.status_code >= 400 and DUMP_DIR:
        _dump(raw, upstream.status_code)
    return upstream


DUMP_DIR = os.getenv("DUMP_DIR", "")


def _dump(raw: bytes, status: int):
    try:
        os.makedirs(DUMP_DIR, exist_ok=True)
        name = os.path.join(DUMP_DIR, f"chat-{status}-{int(time.time()*1000)}.json")
        with open(name, "wb") as f:
            f.write(raw)
        log.info("saved rejected request: %s", name)
    except OSError as exc:
        log.warning("could not save request: %s", exc)


@app.get("/v1/models")
async def list_models(request: Request):
    """Ollama's models plus the embedding models from EMBED_ROUTES."""
    if not EMBED_ROUTES:
        return await forward(request, b"")
    upstream = await client.get(OLLAMA_URL + "/v1/models")
    if upstream.status_code != 200:
        return JSONResponse(upstream.json() if upstream.content else {}, status_code=upstream.status_code)
    data = upstream.json()
    items = data.setdefault("data", [])
    present = {m.get("id") for m in items}
    for name in EMBED_ROUTES:
        if name not in present:
            items.append({"id": name, "object": "model", "created": int(time.time()),
                          "owned_by": "local", **EMBED_MODEL_META})
    return JSONResponse(data)


@app.post("/v1/embeddings")
async def embeddings(request: Request):
    raw = await request.body()
    try:
        model = json.loads(raw).get("model")
    except (ValueError, AttributeError):
        model = None
    target = EMBED_ROUTES.get(model)
    log.info("embeddings model=%s -> %s", model, target or "ollama")
    if target:
        try:
            return await forward(request, raw, base_url=target)
        except httpx.HTTPError as exc:
            log.warning("embeddings service unavailable: %s", exc)
            return JSONResponse(
                {"error": {"message": f"embedding service unavailable: {type(exc).__name__}",
                           "type": "server_error"}},
                status_code=503,
            )
    return await forward(request, raw)


@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"])
async def passthrough(path: str, request: Request):
    return await forward(request, await request.body())

Share with:


Leave a Reply

Your email address will not be published. Required fields are marked *