Polyweave

@polyweave/context-assembler (1.0.6)

Published 2026-07-11 15:00:17 +00:00 by Dvorak

Installation

@polyweave:registry=https://hub.kl1.tenere.ai/api/packages/Polyweave/npm/
npm install @polyweave/context-assembler@1.0.6
"@polyweave/context-assembler": "1.0.6"

About this package

@polyweave/context-assembler

Assemble LLM context from multiple sources with relevance ranking, token budget management, and multi-format output. Provides source adapters (database, vector store, AtomStore, web), ranking strategies (vector similarity, keyword, graph distance), and output formatters (LLM prompt, structured data).

Synopsis

import { ContextAssembler, DatabaseSource, VectorSource, AtomStoreSource, WebSource, StateSource, StateSearchSource } from '@polyweave/context-assembler';

const assembler = new ContextAssembler({
  sources: {
    specs: new DatabaseSource(db, 'specs'),
    articles: new VectorSource(vectorDB, 'articles'),
    knowledge: new AtomStoreSource(atomStore, 'facts')
  },
  strategy: 'vector-similarity',
  tokenBudget: 4000,
  formatter: 'llm-prompt'
});

const context = await assembler.assemble({
  primary: { source: 'specs', query: { id: 'story-123' } },
  related: [{ source: 'articles', query: { category: 'AI' }, limit: 3 }],
  persona: 'tech-reporter'
});
// → { systemPrompt, userPrompt, metadata, tokenCount }

Install

npm install @polyweave/context-assembler

Why

LLM calls need relevant, budgeted context assembled from heterogeneous sources. The context assembler normalizes database queries, vector searches, knowledge graph lookups, and web fetches into a unified prompt format. Ranking strategies sort results by relevance. Token budget management ensures the final prompt fits within model context windows. Source adapters and strategies are pluggable — add custom sources without modifying the assembler core.

API

ContextAssembler

The main class. Constructor:

Parameter Type Default Description
sources object Map of source name to source adapter instance
strategy string | function 'vector-similarity' Ranking strategy name or custom function
tokenBudget number 4096 Maximum tokens for assembled context
formatter string | function 'llm-prompt' Output format name or custom formatter

Methods:

assemble(options)

Returns Promise<{ systemPrompt, userPrompt, metadata, tokenCount }>.

Parameter Type Description
primary { source, query, limit? } Primary context source and query
related [{ source, query, limit }] Secondary context sources
persona string | object Persona ID or persona object for prompt styling
format string Override output format

Source Adapters

Each source adapter implements fetch(query) returning Promise<Array<{ id, content, metadata }>>.

DatabaseSource(db, table)

SQL database source. query is a WHERE clause or ID lookup. Returns rows as context items.

VectorSource(vectorDB, collection)

Vector database source. query is a search string. Returns nearest neighbors by embedding similarity.

AtomStoreSource(atomStore, type)

AtomStore (knowledge graph) source. query filters atoms by type. Returns matching facts.

WebSource(searchAPI)

Web search source. query is a search string. Returns web page excerpts.

StateSource(stateStore, entityType)

Polyweave state store source. Queries entity data from a MultiStateStore.

StateSearchSource(searchEngine)

Polyweave state search source. Queries indexed state with full-text/filter search.

Ranking Strategies

'vector-similarity' (default)

Ranks results by cosine similarity between query embedding and result embeddings. Best for semantic relevance.

'keyword-ranking'

Ranks results by TF-IDF or keyword overlap with the query. Best for exact-match scenarios.

'graph-distance'

Ranks results by graph traversal distance from a seed node. Best for knowledge-graph context.

Custom strategies are functions (query, results) => results that reorder or filter the results array.

Output Formatters

'llm-prompt'

Formats context as a structured prompt with system instructions, user message, and inline context.

'structured'

Returns raw structured data: { items, sources, metadata }.

Custom formatters are functions (items, options) => { systemPrompt, userPrompt, metadata, tokenCount }.

Errors

  • Error('Source not found: <name>') — primary or related source references an unregistered source name
  • Error('Strategy not found: <name>') — strategy name not registered
  • Error('Formatter not found: <name>') — formatter name not registered

The assembler catches source adapter errors and includes them in metadata rather than throwing, so a single failing source does not block assembly.

Status

This package is scaffolded. Some source adapters and strategies may be partially implemented. See TODO.md for roadmap.

Tests

npm test

8 tests covering assembler construction, source registration, ranking strategy application, and token budget enforcement.

Requirements

Node.js 22 or later. ESM only.

Dependencies

Dependencies

ID Version
@polyweave/core *
@polyweave/state-search *

Development Dependencies

ID Version
@rigor/core *

Keywords

llm context assembler polyweave rag
Details
npm
2026-07-11 15:00:17 +00:00
4
John Dvorak
SEE LICENSE IN LICENSE
latest
11 KiB
Assets (1)
Versions (4) View all
1.0.6 2026-07-11
1.0.3 2026-07-11
1.0.2 2026-07-10
1.0.1 2026-07-10