Lompat ke konten

Pelajaran 22 ยท Projects and Reference

Project: A Local Llama Chat Assistant

Build a command-line assistant with history trimming, commands, error handling and a swappable backend, testing it with a stand-in before using local Llama.

In this project you build a small command-line chat assistant that runs on your computer. The trick that makes it testable: the part that talks to the model is one function that you can swap. You develop with a fake backend, then plug in a local Llama.

Requirements

  • Keep a system message and recent history.
  • Stay within a context budget.
  • Support /reset and /quit.
  • Show a clear message if the server is not running.
  • Do not write conversations to disk unless the user asks.

Design

flowchart TD
  I["Read input"] --> C{"Command?"}
  C -->|yes| X["Run command"]
  C -->|no| H["Add to history and trim"]
  H --> B["Backend function"]
  B --> O["Print reply and store it"]

Only the backend function knows how the model is reached.

The core, with a stand-in backend

You can run it here. It uses scripted input instead of the keyboard.

Python Stand-in: chat core with a fake backend

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Watch how the number of visible messages stays small because the budget is tiny. A failed call removes the unanswered user message, so the history stays consistent.

The real backend

Replace the fake with this on your own computer. It needs Ollama running with the model downloaded (see Run Llama with Ollama).

Python
import json
import urllib.error
import urllib.request

def ollama_backend(messages, model="llama3.2:3b"):
    body = json.dumps({"model": model, "messages": messages, "stream": False,
                       "options": {"num_ctx": 4096, "temperature": 0.3}}).encode()
    request = urllib.request.Request("http://localhost:11434/api/chat", data=body,
                                     headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(request, timeout=180) as response:
            reply = json.load(response)
    except urllib.error.URLError as error:
        raise ConnectionError(error.reason) from error
    text = reply["message"]["content"]
    if reply.get("done_reason") == "length":
        text += " [reply cut off by a length limit]"
    return text

if __name__ == "__main__":
    bot = Assistant(ollama_backend, budget=3000)
    while True:
        line = input("you: ")
        if line.strip() == "/quit":
            break
        print("bot:", bot.handle(line))

Put the Assistant class and this function in the same file. Note two choices. The history budget (3,000 estimated tokens) leaves room under the 4,096-token context for the reply. The long timeout allows for a slow first model load. Compare your estimate with the real prompt_eval_count and adjust it.

Test it

Write tests with the fake backend:

  • /reset leaves only the system message.
  • The system message survives trimming.
  • A ConnectionError leaves no half turn in history.
  • Empty input is not sent.

Then run a manual script of ten realistic messages against the real model. Note wrong facts, odd formatting and speed.

Extensions

  1. Add streaming so words appear as they are generated.
  2. Add /model to switch between two local models.
  3. Add /save that writes the chat to a file only on request, and warn that it may contain private data.
  4. Summarize old turns instead of deleting them. Test whether the summary loses important facts.
  5. Keep the system prompt in a file and keep versions of it.

Keep the model's output separate from your program's commands. A reply that contains "/reset" should just be text.

Build it in steps

Work in this order, and make each step run before you continue.

  1. Fake backend and one turn. Send one message and print the reply.
  2. History. Keep the turns and show that a second request includes the first.
  3. Commands. Add /reset and /quit, handled by your program before anything reaches the model.
  4. Budget. Add trimming and a test that shows old turns disappearing while the system message stays.
  5. Errors. Make the fake backend raise ConnectionError and check the history afterward.
  6. Real model. Swap in the Ollama function and try your ten test messages.

Small steps make bugs easy to locate. If a problem appears only after step six, you know it belongs to the backend, the model or the settings.

Improve the budget

The estimate of four characters per token is rough, and it is worse for some languages and for code. Two better options exist. You can count with the tokenizer of your model, or you can read prompt_eval_count from each reply and compare it with your estimate. Notice that some runtimes may report fewer evaluated prompt tokens when they reuse cached work, so read the field's documentation for your version before you treat it as the full prompt size.

Decide how it should behave

Write a short system message that states the assistant's job and limits, for example that it answers briefly, admits uncertainty and does not claim to have performed actions it cannot perform. This assistant has no tools, so it cannot send mail or change files. Test that it does not pretend otherwise, and tell your users what it can do.

Check your work

Before you call the project finished, run through this review.

  • Start the program with the model server stopped. Is the message clear, and does the program keep running?
  • Paste a very long message. Does the program handle a text that alone exceeds your budget? The trimming function keeps the newest message, so decide whether to reject or shorten it.
  • Ask the assistant what you said many turns ago. After trimming, it cannot know, and a model may guess. Consider telling users that old turns are forgotten.
  • Press Ctrl+C. Decide whether to exit quietly instead of showing a long error.
  • Search your code for secrets, saved transcripts and debug printing of messages.

Write one sentence for each item about what happened. Fix the ones that would confuse a real user.

What you practiced

You separated model access from program logic, handled history and errors and tested without a model.

Where to go next. This design is the skeleton of larger applications. A web interface can call the same Assistant class, with one instance and one history for each user. Retrieval can add source passages before the backend call, and tools can be handled in a loop inside it. In each case, keep the backend separate, keep the history rules in one place and keep your tests. If you give the assistant to other people, add authentication, per-user limits and a clear statement about what is stored. Never share one history between users, because one person could then see another person's messages.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why make the backend a single swappable function?

    Separating model access makes testing and swapping simple.
  2. 2. Which message should trimming protect?

    The system message holds the standing instructions.
  3. 3. What does the program do if the server is unreachable?

    Clear errors and consistent history avoid confusing behavior.

Summary

  • A small core handles history, commands and errors.
  • A swappable backend enables tests with a fake.
  • The real backend calls a local server with a timeout and an explicit context.
  • Do not save conversations without the user's request.

Next: Project: Private Document Q&A with Llama

Progres Anda disimpan di browser ini. Tidak perlu akun.