Build a Private AI Assistant on Ubuntu: Connect LLM APIs with Secure Remote Access

    This guide walks through deploying a self-hosted AI assistant on an Ubuntu server, covering framework selection criteria, user and Node.js environment preparation, installation troubleshooting, LLM API integration with secure key storage, and safe remote access through SSH tunneling. It focuses on practical verification steps and common error diagnosis to help you get a production-ready setup without exposing services to the public internet.

    1. Three Checks Before Choosing a Framework

    Before installing any framework, verify the following three aspects.

    1. API compatibility: Confirm the framework allows you to configure a custom model provider, including Base URL, API Key, and model name. If these fields cannot be set, the framework cannot connect to third-party LLMs.
    2. Runtime environment: Use the following commands to check the required Node.js version and recent update activity.
    1. npm view <package-name> engines
    2. npm view <package-name> time.modified

    The engines field lists the supported Node.js version range. time.modified shows the most recent publish timestamp. A project unchanged for over a year may be incompatible with newer Node.js versions or recent model API changes.

    1. Listen address and license: Ensure the web interface defaults to listening on 127.0.0.1 only, and confirm the license permits your intended usage.

    All placeholders in this article must be replaced before execution; otherwise commands will fail.

    Placeholder Meaning Replacement
    <package-name> npm package name of the framework Use the framework you chose
    <command-name> Command provided after framework installation Refer to the framework documentation
    <model-name> Model identifier from your provider Refer to provider documentation
    <start-command> Command and parameters to launch the framework Refer to the framework documentation
    <server-ip> Public IP address of your server Check your cloud provider console

    2. Preparing a Regular User and Node.js

    Operating persistently as root carries unnecessary risk. Create a regular user first, then use sudo for administrative commands.

    1. sudo adduser deploy
    2. sudo usermod -aG sudo deploy
    3. su - deploy

    adduser will interactively prompt for a password.

    Node.js 20 ends official support in April 2026 already, so this article uses Node.js 22 LTS instead. If the framework’s engines field requires a higher version, select the appropriate one. The commands below download the installation script, let you inspect its contents first, and then execute it — avoiding the risk of piping a remote script directly to bash without review.

    1. sudo apt update
    2. curl -fsSL https://deb.nodesource.com/setup_22.x -o nodesource_setup.sh
    3. less nodesource_setup.sh
    4. sudo -E bash nodesource_setup.sh
    5. sudo apt-get install -y nodejs
    6. node -v
    7. npm -v

    Expected output is v22.x.x for Node.js and npm 10.x or newer. If the version does not satisfy the framework requirements, resolve the version issue before proceeding.

    3. Installing the Framework and Troubleshooting Common Errors

    3.1 Set a User-Level npm Prefix

    Global installation by default writes to system directories, which a regular user cannot modify. Do not use sudo npm install -g, and do not change directory permissions to 777. Instead, point npm to a directory owned by the current user:

    1. mkdir -p ~/.npm-global
    2. npm config set prefix "$HOME/.npm-global"
    3. echo 'export PATH="$HOME/.npm-global/bin:$PATH"' >> ~/.bashrc
    4. source ~/.bashrc
    5. npm config get prefix

    Expected output: /home/deploy/.npm-global.

    3.2 Install and Verify

    1. npm install -g <package-name>@latest
    2. npm ls -g --depth=0
    3. which <command-name>
    4. <command-name> --version

    npm ls -g --depth=0 lists top-level global packages. which outputs the full path of the command; the expected path is under /home/deploy/.npm-global/bin/. If which produces no output, the command is not in PATH — return to Section 3.1 and check the PATH settings.

    3.3 Common Error Handling

    Command not found: Run echo $PATH first and confirm it contains $HOME/.npm-global/bin. If not, re-run source ~/.bashrc from Section 3.1.

    EACCES permission errors: Usually caused by using sudo to install, or because the prefix points to a system directory. Reinstall after setting the user-level prefix described in Section 3.1.

    ENOTEMPTY errors: Typically means leftover files from a previous installation remain in the global directory. Uninstall first, clean the cache, and reinstall:

    1. npm uninstall -g <package-name>
    2. npm cache clean --force
    3. npm install -g <package-name>@latest

    If the error persists, inspect the leftover directory:

    1. ls "$(npm root -g)"

    Confirm the directory name matches the framework package, then remove only that specific directory — do not use wildcards. Back up the directory first or confirm it is no longer needed before deleting.

    Deprecated warnings: Most of the time these only indicate upstream dependencies are no longer maintained and do not affect operation. Verify with these commands:

    1. npm outdated -g
    2. npm audit

    If npm audit reports high-severity or critical vulnerabilities, do not simply wait for upstream fixes. Evaluate three points: whether the service listens only on localhost, whether it processes untrusted input, and whether dependencies can be upgraded. If vulnerabilities cannot be resolved, switch frameworks or isolate the service under a dedicated user while ensuring its port is never exposed to the public network.

    3.4 Setting Listener Address and Port

    Check the framework’s help output to locate settings for listen address and port in its configuration file or environment variables:

    1. <command-name> --help

    Set the listen address to 127.0.0.1 and the port to 3000. Exact field names vary by framework — follow its documentation. The next section will verify this setting.

    4. Connecting to the LLM API and Verifying

    4.1 Storing the API Key Securely

    API keys must never appear in command history, code repositories, or logs. The commands below read the key with hidden input and write it to a file readable only by the current user.

    1. umask 077
    2. mkdir -p ~/.config/ai-assistant
    3. read -rs -p "Enter API Key: " LLM_API_KEY && echo
    4. printf 'LLM_BASE_URL=%s\nLLM_MODEL=%s\nLLM_API_KEY=%s\n' \
    5. "https://api.openai.com/v1" "<model-name>" "$LLM_API_KEY" \
    6. > ~/.config/ai-assistant/env
    7. unset LLM_API_KEY

    read -s hides the input and does not write to shell history. printf is a shell built-in, so the key never appears in the process list. umask 077 gives new files a default permission of 600. The configuration file stays in the home directory, not inside any project folder.

    LLM_BASE_URL must match the provider’s documentation exactly. OpenAI’s base URL example is https://api.openai.com/v1. When the base URL already includes /v1, the request URL is the base URL plus /chat/completions — do not append another /v1. For OpenAI, the complete address is https://api.openai.com/v1/chat/completions. Other providers may use different paths; do not assume the same structure.

    4.2 Verify the API Directly, Bypassing the Framework

    Load the configuration into the current shell, then send a very short test request:

    1. set -a; source ~/.config/ai-assistant/env; set +a
    2. curl -sS -w "\nHTTP %{http_code}\n" \
    3. "$LLM_BASE_URL/chat/completions" \
    4. -K <(printf 'header = "Authorization: Bearer %s"\nheader = "Content-Type: application/json"\n' "$LLM_API_KEY") \
    5. -d "{\"model\":\"$LLM_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"ping\"}],\"max_tokens\":5}"
    6. unset LLM_API_KEY

    The request reads its headers via -K from a process substitution, so the key does not appear in command-line arguments. This test consumes a minimal amount of credits.

    Pass criteria: the final line outputs HTTP 200, and the preceding response body is JSON containing a choices field. The actual text content varies by model and does not need to match.

    For anomalous responses, use this table:

    Symptom Common Cause Resolution
    HTTP 401 Incorrect key, expired key, or extra whitespace Re-save the key per Section 4.1
    HTTP 404 Wrong Base URL, or duplicated /v1 Fix the Base URL against provider docs
    HTTP 400 or model not found Incorrect model name Verify the model identifier from the provider
    HTTP 429 Quota exhausted or rate-limited Check account quota, retry after a delay
    Could not resolve host Wrong domain or DNS failure Check domain spelling and network settings
    Connection refused or timeout Network unreachable or incorrect proxy settings Check network connectivity and proxy environment variables
    CORS error in browser Frontend calling the model API directly Route requests through the local service; never put the key in browser code

    4.3 Start the Service and Confirm Local-Only Listening

    Launch the framework in the first terminal. Running it in the foreground makes log inspection easier:

    1. set -a; source ~/.config/ai-assistant/env; set +a
    2. <start-command>

    Logs should show the service has started. In a second terminal, check the listening address:

    1. ss -ltnp | grep ':3000'

    Expected output should show only 127.0.0.1:3000. If you see 0.0.0.0:3000, *:3000, or [::]:3000, the service is bound to all network interfaces. Stop the service and return to Section 3.4 to fix the listen address.

    Then verify the service itself responds:

    1. curl -sS -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3000/

    Expected output is 200. If the framework provides a dedicated health check path, use that instead per its documentation.

    5. Secure Access via SSH Tunneling

    5.1 Configure Key-Based Authentication

    Generate a key pair on your local machine and upload the public key:

    1. ssh-keygen -t ed25519 -C "laptop-ai-assistant"
    2. ssh-copy-id deploy@<server-ip>
    3. ssh deploy@<server-ip> "echo ok"

    Expected output is ok, with no password prompt. If you set a passphrase when generating the key, you will be asked for it.

    Once key authentication works, disable password login. Keep your current server session open, then edit the SSH configuration:

    1. sudo nano /etc/ssh/sshd_config

    Set PasswordAuthentication to no, then validate syntax and reload the service:

    1. sudo sshd -t
    2. sudo systemctl reload ssh

    No output from sshd -t means the syntax is correct. After reloading, open a new terminal to test key login. Only after confirming success should you close the original session. If the new session fails to log in, use the original session to restore the configuration.

    5.2 Establish the Tunnel

    From your local machine:

    1. ssh -N -L 127.0.0.1:8080:127.0.0.1:3000 deploy@<server-ip>

    -N prevents an interactive remote shell; it only forwards the port. The command produces no output and the terminal remains occupied. This is normal.

    Once the tunnel is established, open http://127.0.0.1:8080 in your browser. You can also test from another local terminal:

    1. curl -sS -o /dev/null -w "%{http_code}\n" http://127.0.0.1:8080/

    Expected output is 200, confirming the tunnel is passing traffic to the service on the server. The SSH connection is encrypted end-to-end, so the API traffic between your local machine and the server cannot be intercepted. At the same time, because the service itself listens only on 127.0.0.1, the server’s public network ports remain closed to the AI assistant service.