Skip to content

NLP Engine: Chat inference with streaming and tool-call parsing #999

Closed

Description

@malibio

Overview

Extend the NLP engine (packages/nlp-engine/) with a new chat module that provides GGUF chat model loading and streaming inference alongside the existing embedding service. This is the core LLM capability that the local agent loop consumes.

The PoC (nodespace-nlp-experiment, April 2026) validated dual-model loading, streaming inference, and tool-call parsing on Metal. This issue formalizes those findings into production code.

Acceptance Criteria

  • ChatInferenceEngine trait fully implemented
  • Streaming works: tokens arrive via callback as they are generated
  • Tool-call parsing: [TOOL_CALLS]search_nodes[ARGS]{"query":"test"} correctly parsed into ToolCallRaw
  • Tool-call parsing handles multiple tool calls in one response
  • Tool-call parsing handles malformed JSON gracefully (returns error, does not panic)
  • Tool-call parsing handles partial [TOOL_CALLS] sentinel split across token boundaries
  • Token counting matches model tokenizer output
  • Dual-model loading: embedding + chat models coexist on Metal without crash
  • GPU scheduling: concurrent requests are serialized (no Metal errors)
  • Unit tests for tool-call parser with corpus of example outputs
  • Integration test: load 3B model, send prompt, receive streamed response
  • Code passes bun run quality:fix

Technical Specifications

New Module

  • packages/nlp-engine/src/chat.rs (or chat/ module)

Chat Inference Implementation

  • Load GGUF chat models via llama-cpp-2 LlamaModel / LlamaContext
  • Streaming: sampler.sample() -> token_to_piece() -> ctx.decode() loop yields tokens individually
  • Chat templates: model.chat_template(None) + model.apply_chat_template() (embedded in GGUF metadata)
  • Temperature: 0.1 default (validated in PoC for reliable tool-call output)
  • Context window: 8192 tokens
  • Implements ChatInferenceEngine trait from Shared types, traits, and interface contracts for agent subsystems #998

Tool-Call Parser

Mistral raw GGUF models use a non-standard format:

[TOOL_CALLS]function_name[ARGS]{"param": "value"}

Multiple calls:

[TOOL_CALLS]search_nodes[ARGS]{"query": "embeddings"}[TOOL_CALLS]search_nodes[ARGS]{"query": "vector search"}

This is NOT the JSON array format from Mistral's API. Parser must handle streaming tokens accumulating into these patterns.

GPU Scheduling

  • Simple mutex or semaphore — one inference at a time
  • Embedding takes priority if both are queued (embeddings are fast, chat is interruptible)
  • Both models share Metal via same LlamaBackend (PoC validated)
  • 3B: combined GPU 2.3 GB (19%), embedding latency unaffected (0.7ms)
  • 8B: combined GPU 5.2 GB (43%), embedding latency ~118ms (acceptable with 30s debounce)

API Notes (from PoC)

  • token_to_str deprecated in v0.1.141+ (use token_to_piece)
  • LlamaBackend initializes once per process
  • Dual LlamaModel instances coexist on same backend sharing Metal

Reference Files

  • packages/nlp-engine/src/embedding.rs — existing embedding service (same crate)
  • packages/nlp-engine/src/config.rs — configuration patterns
  • packages/nlp-engine/Cargo.toml — existing llama-cpp-2 dependency

Exports

  • LlamaChatEngine struct implementing ChatInferenceEngine

Dependencies

Related Issues

Activity

  1. malibio commented on Apr 3, 2026

    @malibio
    CollaboratorAuthor

    Implementation Guide

    Start Here

    1. Read packages/nlp-engine/src/embedding.rs (lines 200-550) — this is the existing inference pattern you'll mirror for chat. Key structures:

      • LlamaState (line 208) — holds LlamaModel + persistent LlamaContext
      • get_or_create_context() (line 240) — lazy context creation with batch size management
      • generate_embedding_llama() (line 518) — the core inference loop using AddBos::Always, LlamaBatch, context decode
    2. Read packages/nlp-engine/src/lib.rs — public API surface. Your chat module will add parallel exports here.

    3. Read packages/nlp-engine/src/config.rs — EmbeddingConfig and resolve_model_path(). You'll create a ChatConfig following the same pattern.

    4. Read packages/nlp-engine/Cargo.toml — llama-cpp-2 is >=0.1.132 with Metal auto-enabled on macOS.

    Key Differences: Chat vs Embedding Inference

    Aspect Embedding (existing) Chat (new)
    Sampler None (embedding mode) Yes — LlamaSampler with temperature 0.1
    Output Single vector Token-by-token stream
    Tokenization AddBos::Always Chat template via model.apply_chat_template()
    Context reuse Persistent across calls Per-session with KV cache
    Batch Single batch, decode once Iterative: sample → decode → sample loop

    Streaming Loop Pattern (from PoC)

    The core generation loop follows this pattern:

    1. Apply chat template to messages → token IDs
    2. Create LlamaBatch from token IDs, decode (prompt ingestion)
    3. Loop:
       a. sampler.sample() → next token
       b. Check for EOS or max_tokens
       c. token_to_piece() → text (NOT token_to_str, deprecated in v0.1.141+)
       d. Emit via callback
       e. Create single-token batch, decode (KV cache extends)
       f. Check for [TOOL_CALLS] sentinel in accumulated text
    

    Tool-Call Parser

    Mistral raw GGUF outputs [TOOL_CALLS]fn_name[ARGS]{json}, NOT the JSON array format from Mistral's API. Your parser must:

    • Accumulate tokens into a text buffer
    • Detect [TOOL_CALLS] sentinel (may be split across token boundaries)
    • Extract function name between [TOOL_CALLS] and [ARGS]
    • Extract JSON between [ARGS] and the next [TOOL_CALLS] or end of output
    • Handle multiple tool calls in one response

    GPU Coexistence

    The PoC validated that embedding model (nomic-embed-text, ~270MB) and chat model coexist on the same LlamaBackend sharing Metal. Both use the global singleton at embedding.rs line 38 (static LLAMA_BACKEND). Your chat model registers with the same LLAMA_STATES vec for cleanup.

    Testing

    • Unit tests for the tool-call parser: create a corpus of example outputs (single call, multiple calls, malformed JSON, partial sentinel)
    • Integration test requires downloading a GGUF model — consider a small test model or mock the LlamaModel for unit tests
    • GPU tests may need to be conditional (CI might not have Metal)
  2. malibio commented on Apr 3, 2026

    @malibio
    CollaboratorAuthor

    Baseline: Frontend tests fail with pre-existing TSConfckParseError (svelte-kit/tsconfig.json not found in worktree). Rust nlp-engine tests will be the relevant baseline for this PR.

  3. self-assigned this
    on Apr 3, 2026
  4. added a commit that references this issue on Apr 3, 2026
    435f9a9
  5. added a commit that references this issue on Apr 3, 2026
    9a9d977
  6. added a commit that references this issue on Jun 22, 2026
    bbd99c3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions