AI Security, Guardrails and Prompt Injection Defence / Prepare the local practice environment

Identify and call the local model

Lesson 5 of 28. Open to read. No account needed.

A saved response can help explain a failure, but it cannot establish that your machine made a model request. Make one benign local call, keep the actual request and response, and record exactly which runner and model produced it. The result establishes a connection observation, not a security score.

Start from the owned workspace and its passing readiness checks. Use the course's AI security practice workbench download. Its fixtures/model-profile.json and starter/security_lab/local_model.py supply the profile and implementation for this lesson. All commands below run from the extracted workbench root in macOS zsh, using your selected CPython 3.13 interpreter, written as python3.

Know what this run will do

The managed profile targets macOS arm64; author execution used an Apple M2 Mac with 16 GB RAM and Metal. This is not a measured hardware minimum. Reading the lesson needs no model; completing the actual-inference task does. Other OS, CPU-only and Windows/WSL paths have not been verified by this course.

The command downloads a pinned portable runner archive from GitHub and a local model package through Ollama's registry infrastructure. Allow about 181 MB plus 523 MB of downloads and several GB of temporary disk space for extraction and cache. It uses CPU/GPU and memory while running. There is no paid API account or cloud inference request. The runner receives OLLAMA_NO_CLOUD=1, listens on a temporary 127.0.0.1 port and uses a separate temporary model cache. The helper does not update an installed runner, reconfigure an existing service or reuse its model cache.

One less obvious effect matters: this pinned runner initialises keys under ~/.ollama even with cloud features disabled. The helper handles that explicitly:

  • If a complete, regular key pair already exists, it preserves those files and compares their metadata after the run. It does not print their contents.
  • If the directory is absent, the helper creates it exclusively, captures the newly generated key files and removes only those unchanged files during cleanup. It removes the directory only if empty.
  • Existing incomplete/symlink state, changed keys or unexpected contents are preserved. The result needs inspection; deleting someone else's configuration is not a setup fix.

Keep this a private disposable workspace, and avoid starting another Ollama installation during the managed run. The helper leaves user/system home variables intact. Its local-only configuration is not a network-capture audit.

Read the profile before using it

manifest.json identifies the model-profile file and its fingerprint separately from the three readiness fixtures. local_model.py checks that fingerprint before using its values. The runner archive also has an upstream size and SHA-256 check. Preserve the supplied profile rather than editing its checks to accept an unexpected download.

Recorded identityValue
Runner release0.40.9
Model tagqwen3:0.6b
Full model digest7df6b6e09427a769808717c0a93cadc4ae99ed4eb8bf5ca557c90846becea435

A tag is a convenient name that may later point to different content. The full digest identifies the package observed in this course's profile. The helper checks the server's version and model listing before scheduling chat. A wrong version, missing model or changed digest stops the task; do not silently report another model as this one.

Tokens and the bounded request

A token is a model-specific piece of text. One character, byte or word is not necessarily one token. A context window limits the sequence available to generation, including the chat template, instructions, supplied messages and output. A user-message character limit therefore cannot establish a token budget on its own.

This exact request excerpt is the complete request object in the supplied profile. It is JSON data sent by the helper, not a terminal command:

{
  "model": "qwen3:0.6b",
  "messages": [
    {"role": "system", "content": "Draft a short support observation from synthetic data. Do not claim that you changed a ticket."},
    {"role": "user", "content": "Write one short sentence about this summary: CEDAR-101: Cable disconnected."}
  ],
  "stream": false,
  "think": false,
  "keep_alive": "2m",
  "options": {"num_ctx": 2048, "num_predict": 128, "temperature": 0.7, "seed": 101}
}

model chooses the named local package after identity verification. The two messages separate application guidance from the synthetic task. stream: false requests one JSON response rather than a stream of response fragments. think: false selects this model's non-thinking mode; it is not a security control. keep_alive: "2m" requests a short in-memory retention period during the owned session; the managed helper stops its own runner at the end anyway.

num_ctx: 2048 selects the course's context size, and num_predict: 128 caps generated tokens. The short supplied prompt leaves room for the template and reply; inspect prompt_eval_count and eval_count in the actual response. Do not fill the entire context with user text and assume the instructions and output need no space. A response stopped for length is incomplete evidence.

temperature affects selection among possible continuations, and seed records a repeat setting. These choices help describe this run; they do not guarantee identical replies across releases or hardware. The later experiment will hold chosen settings fixed while comparing prompt configurations. Unspecified generation options retain the pinned runner/package defaults, which is another reason to record both identities with the explicit request.

The helper additionally caps this workflow at one chat attempt, a 65,536-byte response read, a 10-second blocking socket timeout and a checked 30-second workflow deadline. Download/startup have separate setup budgets. A deadline rejects a late result; it is not hard preemption. A socket timeout alone does not establish that inference stopped. Owned-process cleanup is separate evidence of stopping this local runner.

Make and inspect one actual call

From the extracted root, choose a fresh run name:

python3 -B starter/security_lab/workspace.py start --run model-a
python3 -B starter/security_lab/local_model.py managed --run model-a

The first command creates the marked output directory. The second verifies the portable archive, starts its own loopback process, pulls the local package, checks runner/model identity, makes one benign chat request and cleans up its temporary process/cache. Downloads can take several minutes. It writes the actual observation to runs/model-a/local-chat.json, preserving existing observations rather than replacing them. There is no retry loop for chat and no fallback to a hosted service or saved response.

Inspect the JSON file in your editor. These illustrative selected fields describe a completed connection; your response wording, times and token counts will vary:

{
  "status": "observed",
  "mode": "actual-local-inference",
  "chat_calls": 1,
  "ticket_effects": 0
}

Read beyond that status. Check the complete model_digest, runner_release, runner_archive_sha256, request/options, actual response.message.content, done/done_reason, token counts, elapsed time and cleanup fields. A completed response establishes that a local generation was observed under these settings. Whether its sentence faithfully describes the cable is a separate task-quality judgement. No ticket API or approval operation exists in this connection path, so a model sentence claiming a change would still cause no ticket change. The mode field labels the attempted route; count actual inference only when the completed response and status support it. A setup failure on that route can still have zero chat calls.

An error, timeout, length stop or late result is recorded as inconclusive and returns a nonzero exit. Preserve it. Diagnose the error before deliberately starting a new run; do not replace it with a prewritten success example.

Trace the adapter instead of treating it as magic

Open starter/security_lab/local_model.py. request_json builds HTTP requests only to a numeric port on 127.0.0.1 and a small set of API paths. Its opener disables proxy use for local traffic and refuses redirects. Version/model checks use read requests; /api/chat uses a JSON request body. This exact excerpt bounds the response read:

with local_opener().open(request, timeout=timeout) as response:
    raw = response.read(limit + 1)
if len(raw) > limit:
    raise ValueError("Model response byte limit exceeded")
return json.loads(raw)

request is the prepared local HTTP request; timeout bounds blocking socket operations. Reading one byte beyond limit distinguishes a response within the cap from an oversized response. The helper rejects oversize data before parsing it. Parsing the server response does not validate a proposed ticket action; later lessons teach that separate contract. No generated text is run as Python, a shell command or a tool action here.

verify_identity rejects mismatched runner/model metadata before chat. observe_chat records the request and one scheduled attempt, then classifies incomplete/late responses. managed owns download, process and temporary-cache lifecycle in try/finally; it stops only the process group it started. The key-state checks preserve pre-existing files and refuse unclear ownership. An abrupt machine shutdown cannot be promised the same cleanup as a normal exit; inspect state after interruption before continuing.

Diagnose a failure without changing an existing service

Run the disclosed adapter checks from the extracted root:

python3 -B -m unittest discover -s tests -p 'test_local_model.py' -v

These eight tests use synthetic HTTP responses, including wrong versions, wrong digests, redirects, oversize data and truncation. Their passing result checks the adapter's behaviour; it is not a live model result.

Now attempt the independent task. Predict the observation, then run:

python3 -B starter/security_lab/local_model.py diagnose-unavailable

This command reserves its own local socket without listening and tries a version request to it. It cannot accidentally use a different existing service on that port. Explain which part failed, whether a model was contacted and whether this outcome says anything about the quality of the prompt. Then explain why changing the expected digest after a mismatch is a different profile decision, rather than a connection repair.

Hint 1

Separate transport, identity verification and generation. An unavailable listener prevents the later stages from being observed at all.

Hint 2

A name can remain the same while its package changes. Ask what evidence would be lost if you replaced the recorded digest just to make the comparison pass.

Answer and reasoning

The controlled fault should report unavailable-as-expected, mode: controlled-local-fault and zero chat calls. It demonstrates diagnosis of an unavailable local listener, not a model refusal or a bad prompt. It creates no observation file and neither starts nor changes an installed service. The fixed socket is released when the command ends.

A digest mismatch means the selected package does not match the pinned profile. Preserve the observation and verify the intended source/version. Changing the expected digest would define a different profile requiring its own recorded verification; it would erase the reason for this check if done silently. Never overwrite a working installation or stop unrelated services as a routine fix. A successful independent answer identifies the failed stage and the missing inference evidence, rather than merely quoting an exit code.

Resume and remove only owned outputs

On normal completion or a caught failure, the managed command stops its owned runner, removes its temporary runner/model cache and records key-state cleanup. It preserves local-chat.json and readiness in your marked run. Inspect all cleanup booleans; if any are false, preserve unknown state and diagnose it. The current helper starts a fresh temporary cache each time, so a deliberate new managed run downloads again. Do not delete an existing user's model cache to simulate a clean run.

Keep the observations you need, then from the same extracted root inspect:

python3 -B starter/security_lab/workspace.py clean --run model-a

Only after the plan identifies the owned files you intend to discard:

python3 -B starter/security_lab/workspace.py clean --run model-a --confirm

The allowlist now includes local-chat.json. Unknown files/symlinks still block cleanup before deletion; fixtures, learner source edits, other runs and existing software remain. After an interrupted workflow, inspect the saved report and start a fresh named run. There is no persisted approval to resume here.

Source and evidence limits

The Chat API, FAQ, pinned release, macOS requirements, package and model card support the runner/model contract. Pinned key-initialisation source explains its home-directory side effect. Python urllib supports the HTTP adapter; Python version status supports choosing a maintained interpreter. Actual connection evidence, fixture adapter tests and later attack/effect experiments answer different questions. A finite local run establishes none of universal injection defence, production authentication or another platform's compatibility.

23 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy