=============== LIBRARY RULES =============== From library maintainers: - This is not a conventional Western (European) Culture libraries, therefore, LLM agent using this are assumed to be biased and have some transparent thinking todo before interacting with their human companion. ### Quick Start Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/README.md A quick example demonstrating how to use the `decompose` function to break down a complex prompt into a structured format. ```APIDOC ## Quick Start ```typescript import { decompose } from 'ava-langchain-prompt-decomposition'; const result = decompose( 'Research the existing patterns. Build the new module. Test the integration.' ); console.log(result.json); // Full PDE JSON console.log(result.markdown); // Human-readable breakdown ``` ``` -------------------------------- ### Installation Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/README.md Install the ava-langchain-prompt-decomposition package using pnpm. ```APIDOC ## Installation ```bash pnpm add ava-langchain-prompt-decomposition ``` ``` -------------------------------- ### Install the package Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/state-machine-spec/README.md Use npm to install the state machine specification library. ```bash npm install ava-langchain-state-machine-spec ``` -------------------------------- ### Install ava-langchain-relational-intelligence Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/relational-intelligence/README.md Install the package using npm. ```bash npm install ava-langchain-relational-intelligence ``` -------------------------------- ### Install the package Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/README.md Use pnpm to add the library to your project. ```bash pnpm add ava-langchain-prompt-decomposition ``` -------------------------------- ### Install @langchain/eslint Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/internal/eslint/README.md Install the shared ESLint configuration as a development dependency. ```bash pnpm add -D @langchain/eslint ``` -------------------------------- ### Navigate to Langchainjs Directory Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/CONTRIBUTING.md Clone the Langchainjs repository and navigate into the project directory to begin setup. ```bash cd langchainjs ``` -------------------------------- ### Install Narrative Tracing Package Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/narrative-tracing/README.md Install the narrative tracing package using npm. ```bash npm install @langchain/narrative-tracing ``` -------------------------------- ### Install Dependencies and Build Core Package Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/AGENTS.md Installs project dependencies using pnpm and then builds the core LangChain package. This is a prerequisite for building other packages. ```bash pnpm install pnpm --filter @langchain/core build ``` -------------------------------- ### Install AvaLangStack Packages Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/docs/getting-started.md Install individual AvaLangStack packages using npm, pnpm, or yarn. ```bash # Using npm npm install ava-langchain-prompt-decomposition npm install ava-langchain-inquiry-routing npm install ava-langchain-relational-intelligence npm install ava-langchain-narrative-tracing npm install ava-langchain-state-machine-spec ``` ```bash # Using pnpm pnpm add ava-langchain-prompt-decomposition pnpm add ava-langchain-inquiry-routing pnpm add ava-langchain-relational-intelligence pnpm add ava-langchain-narrative-tracing pnpm add ava-langchain-state-machine-spec ``` ```bash # Using yarn yarn add ava-langchain-prompt-decomposition yarn add ava-langchain-inquiry-routing yarn add ava-langchain-relational-intelligence yarn add ava-langchain-narrative-tracing yarn add ava-langchain-state-machine-spec ``` -------------------------------- ### Provider Package Structure Example Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/AGENTS.md Illustrates the recommended directory structure for new LangChain.js provider packages, including configuration files and source directories. ```text libs/providers/langchain-{provider}/ ├── package.json ├── tsconfig.json ├── tsdown.config.ts ├── vitest.config.ts ├── eslint.config.ts ├── turbo.json ├── README.md ├── LICENSE └── src/ ├── index.ts ├── chat_models/ │ ├── index.ts │ └── tests/ │ ├── index.test.ts │ ├── index.int.test.ts │ ├── index.standard.test.ts │ └── index.standard.int.test.ts └── embeddings.ts (if applicable) ``` -------------------------------- ### Run Development Server Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/environment_tests/test-exports-vercel/README.md Use these commands to start the Next.js development server. Open http://localhost:3000 in your browser to view the application. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` -------------------------------- ### Install Inquiry Routing Package Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/inquiry-routing/README.md Add the inquiry routing and prompt decomposition packages to your project using pnpm. ```bash pnpm add ava-langchain-inquiry-routing ava-langchain-prompt-decomposition ``` -------------------------------- ### Quick Start Inquiry Generation Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/inquiry-routing/README.md Run the full inquiry generation pipeline using the convenience function. ```typescript import { generateInquiries } from "ava-langchain-inquiry-routing"; import { decompose } from "ava-langchain-prompt-decomposition"; const pde = await decompose("Build a knowledge graph grounded in indigenous epistemology..."); const result = generateInquiries(pde.decomposition); console.log(`Generated ${result.batch.total} inquiries`); console.log(result.markdown); ``` -------------------------------- ### Install Dev Release of Langchain Core Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/CONTRIBUTING.md Use this command to install the latest development release of the @langchain/core package. For specific versions, append the version number and commit SHA. ```bash npm install @langchain/core@dev ``` ```bash npm install @langchain/core@1.1.0-dev.abc1234 ``` -------------------------------- ### Quick Example: Structural Tension and Prompt Decomposition Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/docs/getting-started.md Demonstrates evaluating structural tension between two concepts and decomposing a complex prompt using AvaLangStack. ```typescript import { StructuralTensionChain } from "ava-langchain-relational-intelligence"; import { decompose } from "ava-langchain-prompt-decomposition"; async function runExample() { // Evaluate structural tension const chain = new StructuralTensionChain(); const vector = chain.evaluate( "Monolith with no tests, team works in silos", "Microservices with full coverage, daily ceremonies" ); console.log(`Tension magnitude: ${vector.magnitude}`); console.log(`Direction: ${vector.direction}`); // Decompose a complex prompt const result = await decompose("Build a knowledge graph with ceremony gating..."); console.log(result.markdown); } runExample(); ``` -------------------------------- ### Basic Unit Test with Vitest Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/AGENTS.md A simple unit test example using Vitest. This demonstrates mocking a `FakeChatModel` and asserting its output. ```typescript import { test, expect, describe } from "vitest"; import { FakeChatModel } from "@langchain/core/utils/testing"; test("should do something", async () => { const model = new FakeChatModel({}); const result = await model.invoke([["human", "Hello!"]]); expect(result.content).toBe("Hello!"); }); ``` -------------------------------- ### Integrate State Machine with FireKeeper Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/state-machine-spec/README.md Example showing how to load a specification, validate it, and use FireKeeper to gate transitions. ```typescript // See examples/src/accountability-routing/agent_session_router.ts import { parseStateMachineSpec, validateStateMachineSpec } from "ava-langchain-state-machine-spec"; import { FireKeeper } from "ava-langchain-relational-intelligence"; import spec from "./accountability_spec.json" assert { type: "json" }; // 1. Load and validate the spec const machine = parseStateMachineSpec(spec); const validation = validateStateMachineSpec(machine); if (!validation.valid) throw new Error(validation.errors.join(", ")); // 2. FireKeeper gates every prompt before the graph advances const keeper = new FireKeeper("Build with relational care."); const review = keeper.processPrompt("Retrieve papers from knowledge graph"); if (!review.accepted) throw new Error(`Blocked: ${review.feedback}`); // 3. Advance the state machine const next = machine.states[machine.initialState].allowedTransitions[0]; console.log(`State: ${machine.initialState} → ${next}`); ``` -------------------------------- ### Quick Start: Narrative Tracing Handler Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/narrative-tracing/README.md Initialize and use the NarrativeTracingHandler for simple tracing of story generation, logging beats, and performing three-universe analysis. ```typescript import { NarrativeTracingHandler, NarrativeTraceOrchestrator, NarrativeTraceFormatter, NarrativeEventType, } from '@langchain/narrative-tracing'; // Create handler for simple tracing const handler = new NarrativeTracingHandler({ storyId: 'story_123', sessionId: 'session_456', }); // Start story generation const traceId = handler.startStoryGeneration(); // Log beat creation handler.logBeatCreation( 'beat_001', 'The story begins with a mysterious event...', 1, 'inciting_incident', { emotionalTone: 'intrigue' } ); // Log three-universe analysis handler.logThreeUniverseAnalysis({ eventId: 'evt_123', engineerIntent: 'feature_implementation', engineerConfidence: 0.8, ceremonyIntent: 'co_creation', ceremonyConfidence: 0.7, storyEngineIntent: 'rising_action', storyEngineConfidence: 0.85, leadUniverse: 'story_engine', coherenceScore: 0.82, }); // End generation handler.endStoryGeneration(totalMs); ``` -------------------------------- ### Example generated import constants Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/internal/build/README.md The importConstantsPlugin generates a file containing an array of optional import entrypoints. ```typescript /** Auto-generated by import-constants plugin. Do not edit manually */ export const optionalImportEntrypoints: string[] = [ "langchain_community/tools/calculator", "langchain_community/embeddings/openai", ]; ``` -------------------------------- ### Accountability Routing Workflow Example Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/relational-intelligence/README.md Demonstrates an end-to-end integration using FireKeeper for gating agent actions and a state machine for routing through the accountability lifecycle. Ensure the state machine specification is correctly parsed and the FireKeeper is initialized with the session vision. ```typescript // See examples/src/accountability-routing/agent_session_router.ts import { FireKeeper, ValueGate } from "ava-langchain-relational-intelligence"; import { parseStateMachineSpec } from "ava-langchain-state-machine-spec"; import spec from "./accountability_spec.json" assert { type: "json" }; // 1. Parse and validate the state machine specification const machine = parseStateMachineSpec(spec); // 2. Initialise a FireKeeper with the session vision const keeper = new FireKeeper("Research relational AI architectures with care."); // 3. Gate every action through the FireKeeper before advancing state const review = keeper.processPrompt("Retrieve relevant papers from the knowledge graph"); if (!review.accepted) { throw new Error(`FireKeeper blocked: ${review.feedback}`); } if (review.requiresHumanEngagement) { console.log("Human engagement requested:", review.feedback); } // 4. Advance the state machine only when the FireKeeper approves const transition = machine.states[machine.initialState].allowedTransitions[0]; console.log(`Advancing to: ${transition}`); ``` -------------------------------- ### Type Guard Example for LangChain Messages Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/AGENTS.md Demonstrates the recommended way to check message types in LangChain.js using static `isInstance` methods instead of `instanceof`. ```typescript AIMessage.isInstance(message) ``` -------------------------------- ### Quick Start decomposition Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/README.md Basic usage of the decompose function to process a prompt string. ```typescript import { decompose } from 'ava-langchain-prompt-decomposition'; const result = decompose( 'Research the existing patterns. Build the new module. Test the integration.' ); console.log(result.json); // Full PDE JSON console.log(result.markdown); // Human-readable breakdown ``` -------------------------------- ### Evaluate Structural Tension and Decompose Prompt (TypeScript) Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/README.md Demonstrates evaluating structural tension between two states and decomposing a complex prompt using AvaLangStack libraries. Ensure the respective packages are installed. ```typescript import { StructuralTensionChain } from "ava-langchain-relational-intelligence"; import { decompose } from "ava-langchain-prompt-decomposition"; // Evaluate structural tension const chain = new StructuralTensionChain(); const vector = chain.evaluate( "Monolith with no tests, team works in silos", "Microservices with full coverage, daily ceremonies" ); console.log(`Tension magnitude: ${vector.magnitude}`); console.log(`Direction: ${vector.direction}`); // Decompose a complex prompt const result = await decompose("Build a knowledge graph with ceremony gating..."); console.log(result.markdown); ``` -------------------------------- ### Example generated SecretMap Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/internal/build/README.md The lcSecretsPlugin generates a TypeScript interface documenting all secrets used in the package. ```typescript /** Auto-generated by lc-secrets plugin. Do not edit manually */ export interface OptionalImportMap {} export interface SecretMap { OPENAI_API_KEY?: string; OPENAI_ORG_ID?: string; } ``` -------------------------------- ### Scaffolding New Integrations with CLI Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/AGENTS.md Use the `create-langchain-integration` CLI command to quickly scaffold new provider packages, setting up the necessary file structure and configuration. ```bash npx create-langchain-integration ``` -------------------------------- ### TypeScript Type Test Example Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/CONTRIBUTING.md Example of a type test using vitest's expectTypeOf to assert type signatures and behavior. ```typescript import { expectTypeOf } from "vitest"; expectTypeOf(someFunction).returns.toMatchTypeOf(); ``` -------------------------------- ### Switch to Recommended Node.js Version Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/CONTRIBUTING.md Use nvm to switch to the recommended Node.js version for the project. ```bash nvm use ``` -------------------------------- ### Initialize StrategicDecomposer (With LLM) Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/docs/MULTI_STRATEGY_ARTICLE.md Initializes the StrategicDecomposer with an LLM resource to automatically select the best strategy for complex prompts. Logs the reason for strategy selection. ```typescript import { StrategicDecomposer } from "ava-langchain-prompt-decomposition"; // With LLM — auto-selects best strategy const decomposer = new StrategicDecomposer({ resources: { llm: myChatModel }, }); const { result, selectionReason } = await decomposer.decompose(complexPrompt); console.log(selectionReason); // "Selected hybrid (score: 1.20) for complex prompt..." ``` -------------------------------- ### Initialize StrategicDecomposer (Simple) Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/docs/MULTI_STRATEGY_ARTICLE.md Initializes the StrategicDecomposer with default settings for basic prompt decomposition. ```typescript import { StrategicDecomposer } from "ava-langchain-prompt-decomposition"; // Simple — identical to existing decompose() const decomposer = new StrategicDecomposer(); const { result } = await decomposer.decompose("Build a knowledge graph."); ``` -------------------------------- ### Integration Test for ChatOpenAI Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/AGENTS.md An example of an integration test for `ChatOpenAI`. This test requires API credentials and verifies basic invocation functionality. ```typescript import { describe, test, expect } from "vitest"; import { ChatOpenAI } from "../index.js"; import { HumanMessage } from "@langchain/core/messages"; test("Test ChatOpenAI Generate", async () => { const chat = new ChatOpenAI({ model: "gpt-4o-mini", maxTokens: 10, }); const message = new HumanMessage("Hello!"); const result = await chat.invoke([message]); expect(typeof result.content).toBe("string"); }); ``` -------------------------------- ### Initialize NarrativeTracingHandler with Keys Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/narrative-tracing/README.md Initialize the NarrativeTracingHandler with Langfuse public and secret keys for authentication. ```typescript const handler = new NarrativeTracingHandler({ storyId: 'story_123', publicKey: process.env.LANGFUSE_PUBLIC_KEY, secretKey: process.env.LANGFUSE_SECRET_KEY, }); ``` -------------------------------- ### getBuildConfig(options?) Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/internal/build/README.md Configures the build system for a LangChain package with default settings for formats, targets, and validation. ```APIDOC ## getBuildConfig(options?) ### Description Returns a tsdown configuration object with pre-defined defaults for LangChain packages, including CommonJS/ESM support, ES2022 target, and strict validation. ### Parameters #### Request Body - **options** (BuildOptions) - Optional - A partial object to override default build settings such as target, plugins, or entrypoints. ``` -------------------------------- ### Standard Unit Test Class for Chat Models Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/AGENTS.md Example of extending `ChatModelUnitTests` from `@langchain/standard-tests` to create standardized unit tests for custom chat models. ```typescript import { ChatModelUnitTests } from "@langchain/standard-tests"; class MyChatModelStandardUnitTests extends ChatModelUnitTests< MyChatModelCallOptions, AIMessageChunk > { constructor() { super({ Cls: MyChatModel, chatModelHasToolCalling: true, chatModelHasStructuredOutput: true, constructorArgs: {}, }); } } ``` -------------------------------- ### Run Unit and Integration Tests Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/AGENTS.md Executes unit tests for LangChain packages. For tests requiring API keys, use the `test:integration` command. A single test file can be run using `test:single`. ```bash # Unit tests pnpm --filter langchain test pnpm --filter @langchain/core test # Integration tests (requires API keys) pnpm --filter langchain test:integration # Single test file pnpm --filter test:single ``` -------------------------------- ### NarrativeTracingHandler Class Definition Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/docs/rispecs/narrative-tracing/narrative-tracing.spec.md Outlines the NarrativeTracingHandler class, which extends Langfuse callbacks for narrative-aware tracing, including methods for starting and ending story generation, and logging specific narrative events. ```typescript class NarrativeTracingHandler { storyId: string; sessionId: string | undefined; rootTraceId: string | undefined; correlation: TraceCorrelation | undefined; startStoryGeneration(): void; logBeatCreation(beatId: string, content: string, sequence: number, phase: string): void; logThreeUniverseAnalysis(analysis: Record): void; logRoutingDecision(decision: Record): void; endStoryGeneration(totalMs: number): void; } ``` -------------------------------- ### Build Project in Watch Mode Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/AGENTS.md Use the 'pnpm watch' command to build the project in watch mode, which automatically recompiles code upon changes. ```bash pnpm watch ``` -------------------------------- ### QmdInquiryPlanner Primitive Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/docs/rispecs/inquiry-routing/qmd-inquiry-execution.spec.md Introduces the QmdInquiryPlanner class, which is responsible for converting a batch of routed inquiries into a typed QMD inquiry plan. It handles mapping inquiries to searches and preserving skipped inquiries. ```typescript export class QmdInquiryPlanner { fromRoutedBatch(batch: RoutedInquiryBatch, options?: QmdInquiryPlannerOptions): QmdInquiryPlan; } ``` -------------------------------- ### Core Modules Overview Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/README.md Overview of the core modules available in the prompt decomposition engine. ```APIDOC ## Core Modules | Module | |--------| Description | | `DirectionalDecomposer` | Classifies prompt segments into EAST/SOUTH/WEST/NORTH | | `IntentExtractor` | Extracts primary + secondary intents with confidence and urgency | | `DependencyMapper` | Builds dependency graphs with cycle detection and execution ordering | | `ActionStackBuilder` | Produces final PDE output (JSON/Markdown) | | `MedicineWheelBridge` | Direction↔Quadrant mapping, ceremony detection | | `V0OntologyBridge` | Maps to @medicine-wheel/* V0 package vision | ``` -------------------------------- ### Initialize tsdown configuration Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/internal/build/README.md Create a tsdown.config.ts file in the package root to use the default LangChain build settings. ```typescript import { getBuildConfig } from "@langchain/build"; export default getBuildConfig(); ``` -------------------------------- ### Old vs. New API for Prompt Decomposition Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/docs/STRATEGY_ARCHITECTURE.md Demonstrates the unchanged old API and the new strategy-aware API for prompt decomposition. The old API remains functional, while the new API, using `StrategicDecomposer`, offers enhanced capabilities. ```typescript // Old API — still works exactly the same import { decompose } from "ava-langchain-prompt-decomposition"; const result = await decompose("Build a knowledge graph..."); ``` ```typescript // New API — strategy-aware import { StrategicDecomposer } from "ava-langchain-prompt-decomposition"; const decomposer = new StrategicDecomposer(); const result = await decomposer.decompose("Build a knowledge graph..."); // result.result.decomposition is the same DecompositionResult type ``` -------------------------------- ### Dependency Graph Visualization Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/docs/rispecs/relational-intelligence/relational-intelligence.spec.md Illustrates the dependency relationships between the relational-intelligence module and other AvaLangStack packages. ```text Dependency Graph ava-langchain-relational-intelligence (MedicineWheelFilter, ImportanceStore, SpiralTracker, ValueGate, FireKeeper, LiminalBuffer) │ ┌────────────┼────────────────┐ │ │ │ ▼ ▼ ▼ prompt-decomposition narrative-tracing state-machine-spec (optional peer) (optional peer) (optional peer) │ │ ▼ ▼ prompt-decomposition-engine ← langgraphjs orchestration inquiry-routing-engine narrative-intelligence ← conceptual alignment ``` -------------------------------- ### Run Docker Environment Tests Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/CONTRIBUTING.md Execute this command from the project root to run LangChain.js environment tests using Docker. This verifies compatibility across various JavaScript environments. ```bash pnpm test:exports:docker ``` -------------------------------- ### Run Unit Tests for Langchainjs Packages Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/CONTRIBUTING.md Execute unit tests for specified packages. This command also runs type tests. ```bash pnpm --filter langchain test ``` ```bash pnpm --filter @langchain/core test ``` -------------------------------- ### Run Integration Tests for Langchainjs Packages Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/CONTRIBUTING.md Execute integration tests for a specific package. Ensure .env files are configured for external API access. ```bash pnpm --filter langchain test:single ``` ```bash pnpm --filter langchain test:integration ``` -------------------------------- ### decompose(prompt, options?) Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/README.md Convenience pipeline function that runs all decomposition modules in sequence. It takes a prompt string and optional configuration options. ```APIDOC ## `decompose(prompt, options?)` Convenience pipeline that runs all modules in sequence. ```typescript const result = decompose('Build a knowledge graph with ceremony.', { extractImplicit: true, maxItems: 20, ceremonyThreshold: 0.3, }); result.decomposition // DecompositionResult result.wheelEnriched // WheelEnrichedAnalysis result.json // JSON string result.markdown // Markdown string ``` ``` -------------------------------- ### env.applyEnv Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/internal/test-helpers/README.md Low-level utility to apply environment variables immediately without automatic cleanup. ```APIDOC ## env.applyEnv(envObject) ### Description Applies key-value pairs to process.env immediately. Does not handle automatic cleanup. ### Parameters - **envObject** (object) - Required - Object containing key-value pairs to apply to process.env. If a value is undefined, the key is deleted. ``` -------------------------------- ### Initialize StrategicDecomposer (Multi-Pass) Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/docs/MULTI_STRATEGY_ARTICLE.md Initializes the StrategicDecomposer with an LLM and accuracy preference for multi-pass decomposition, enabling analysis of disagreements between strategies. ```typescript import { StrategicDecomposer } from "ava-langchain-prompt-decomposition"; // Multi-pass for highest quality const decomposer = new StrategicDecomposer({ resources: { llm: myChatModel, preferAccuracy: true }, preferences: { alwaysMultiPass: true }, }); const { result, multiPass } = await decomposer.decompose(ambiguousPrompt); console.log(multiPass.disagreements); // Where strategies saw differently ``` -------------------------------- ### Use InquiryFormatter Module Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/inquiry-routing/README.md Format inquiries into various output formats including QMD, deep-search, markdown, and JSON. ```typescript import { InquiryFormatter } from "ava-langchain-inquiry-routing"; const formatter = new InquiryFormatter(); const qmd = formatter.toQmdQuery(inquiry); // { mode: "vec", query, direction } const ds = formatter.toDeepSearchQuery(inquiry); // { query, academic_context, search_terms } const md = formatter.toMarkdown(batch); // Structured markdown report const json = formatter.toJSON(batch); // JSON serialization ``` -------------------------------- ### Build Langchain Core Package Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/CONTRIBUTING.md Build the core Langchain package. This is a prerequisite for working on other packages. ```bash pnpm --filter @langchain/core build ``` -------------------------------- ### Decompose with options Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/README.md Run the decomposition pipeline with custom configuration options. ```typescript const result = decompose('Build a knowledge graph with ceremony.', { extractImplicit: true, maxItems: 20, ceremonyThreshold: 0.3, }); result.decomposition // DecompositionResult result.wheelEnriched // WheelEnrichedAnalysis result.json // JSON string result.markdown // Markdown string ``` -------------------------------- ### Creating a RunnableStrategicDecomposer Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/docs/STRATEGY_ARCHITECTURE.md Illustrates how to create a `RunnableStrategicDecomposer` by wrapping `StrategicDecomposer` in a `RunnableLambda`, following the pattern used for `RunnableDecomposer`. ```typescript const runnable = new RunnableLambda({ func: async (prompt: string) => { const decomposer = new StrategicDecomposer({ resources: { llm } }); return decomposer.decompose(prompt); }, }); ``` -------------------------------- ### Importing the env helper Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/internal/test-helpers/README.md Import the environment helper module to access testing utilities. ```typescript import { env } from "@langchain/test-helpers/env"; ``` -------------------------------- ### Adaptive Weight Learning Placeholder Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/docs/STRATEGY_ARCHITECTURE.md Future implementation for learning keyword/semantic weights in the HybridStrategy from user feedback. It involves tracking which strategy was used and adjusting weights via exponential moving average. ```typescript // Future: track which strategy's result was actually used // and adjust weights via exponential moving average ``` -------------------------------- ### Convenience Function: generateInquiries Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/inquiry-routing/README.md A convenience function that runs the full inquiry generation pipeline: Generate → Enrich → Route → Format. It takes PDE decomposition output and optional configuration options. ```APIDOC ## generateInquiries(decomposition, options?) ### Description Convenience function that runs the full pipeline: Generate → Enrich → Route → Format. ### Method `generateInquiries` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **decomposition** (object) - Required - PDE decomposition output. - **options** (object) - Optional - Configuration options for the pipeline stages. - **generator** (object) - Options for the InquiryGenerator. - **includeAmbiguities** (boolean) - Optional - Whether to include ambiguities. - **minConfidence** (number) - Optional - Minimum confidence threshold for generated inquiries. - **enricher** (object) - Options for the RelationalEnricher. - **addTwoEyedSeeing** (boolean) - Optional - Whether to add Two-Eyed Seeing annotations. - **routing** (object) - Options for the InquiryRouter. - **confidenceThreshold** (number) - Optional - Confidence threshold for routing inquiries. ### Request Example ```typescript import { generateInquiries } from "ava-langchain-inquiry-routing"; const result = generateInquiries(decomposition, { generator: { includeAmbiguities: true, minConfidence: 0.3 }, enricher: { addTwoEyedSeeing: true }, routing: { confidenceThreshold: 0.4 }, }); ``` ### Response #### Success Response (200) - **batch** (RoutedInquiryBatch) - The batch of routed inquiries. - **markdown** (string) - The inquiries formatted as markdown. - **json** (string) - The inquiries formatted as JSON. ``` -------------------------------- ### Use InquiryRouter Module Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/inquiry-routing/README.md Classify and route inquiries to channels based on keyword matching and confidence thresholds. ```typescript import { InquiryRouter } from "ava-langchain-inquiry-routing"; const router = new InquiryRouter({ confidenceThreshold: 0.4, qmdKeywords: ["schema", "model"], deepSearchKeywords: ["Wilson", "ceremony"], }); const decision = router.classify(inquiry); const routedBatch = router.routeAll(batch); ``` -------------------------------- ### Usage of LangChain ESLint Presets Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/internal/eslint/README.md Import and combine specific ESLint presets like base, node, or browser configurations for your project. ```typescript import { base, node, browser } from "@langchain/eslint"; export default [...base, ...node]; ``` -------------------------------- ### Format Langchainjs Packages Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/CONTRIBUTING.md Apply code formatting using prettier to a specific package. Use 'format:check' to only check for differences. ```bash pnpm --filter langchain format ``` ```bash pnpm --filter langchain format:check ``` -------------------------------- ### env.useVariable Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/internal/test-helpers/README.md Convenience wrapper for setting a single environment variable. ```APIDOC ## env.useVariable(key, value, options) ### Description A convenience wrapper around `useVariables` for setting a single environment variable. ### Parameters - **key** (string) - Required - The name of the environment variable. - **value** (string) - Required - The value to set. - **options** (object) - Optional - Configuration object (same as `useVariables`). ``` -------------------------------- ### Build Specific Langchainjs Packages Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/CONTRIBUTING.md Build individual packages within the Langchainjs project using pnpm filters. ```bash pnpm --filter langchain build ``` ```bash pnpm --filter @langchain/core build ``` -------------------------------- ### LangGraph Bridge: Three Universe Callback Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/narrative-tracing/README.md Create a callback using LangGraphBridge to wire ThreeUniverseProcessor to narrative tracing for manual use. ```typescript import { LangGraphBridge } from '@langchain/narrative-tracing/adapters'; const bridge = new LangGraphBridge(handler); // Create callback for manual use const callback = bridge.createThreeUniverseCallback(); callback({ eventId: 'evt_123', engineerResult: { intent: 'feature_request', confidence: 0.8 }, ceremonyResult: { intent: 'co_creation', confidence: 0.7 }, storyEngineResult: { intent: 'rising_action', confidence: 0.85 }, leadUniverse: 'story_engine', coherenceScore: 0.82, }); ``` -------------------------------- ### Configure cjsCompatPlugin Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/internal/build/README.md Use cjsCompatPlugin to generate barrel files for CommonJS compatibility. Configure the generation mode and specify which file types to generate. ```typescript import { getBuildConfig, cjsCompatPlugin } from "@langchain/build"; export default getBuildConfig({ plugins: [ cjsCompatPlugin({ mode: "generate", shouldGenerate: { dcts: true, cjs: true, dts: true, esm: true, }, }), ], }); ``` -------------------------------- ### Core Module: InquiryFormatter Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/inquiry-routing/README.md Formats inquiries for different output channels, including QMD, Deep Search, Markdown, and JSON. ```APIDOC ## InquiryFormatter ### Description Formats inquiries for different output channels. ### Method `new InquiryFormatter()` ### Parameters None ### Methods #### `toQmdQuery(inquiry)` Formats an inquiry for QMD query. #### `toDeepSearchQuery(inquiry)` Formats an inquiry for Deep Search query. #### `toMarkdown(batch)` Formats a batch of inquiries as markdown. #### `toJSON(batch)` Formats a batch of inquiries as JSON. ### Request Example ```typescript import { InquiryFormatter } from "ava-langchain-inquiry-routing"; const formatter = new InquiryFormatter(); const qmd = formatter.toQmdQuery(inquiry); // { mode: "vec", query, direction } const ds = formatter.toDeepSearchQuery(inquiry); // { query, academic_context, search_terms } const md = formatter.toMarkdown(batch); // Structured markdown report const json = formatter.toJSON(batch); // JSON serialization ``` ``` -------------------------------- ### QMD Query Document Formatter Class Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/docs/rispecs/inquiry-routing/qmd-inquiry-execution.spec.md Provides methods to format inquiry searches into MCP arguments, human-readable query documents, and JSON or Markdown query formats for Miaco. ```typescript export class QmdQueryDocumentFormatter { toMcpArguments(searches: QmdInquirySearch[]): QmdMcpQueryArguments; toQueryDocument(searches: QmdInquirySearch[]): string; toMiacoQueriesJson(plan: QmdInquiryPlan): string; toMiacoQueriesMarkdown(plan: QmdInquiryPlan): string; } ``` -------------------------------- ### Basic Usage of LangChain ESLint Config Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/internal/eslint/README.md Import and export the full LangChain ESLint configuration in your project's eslint.config.ts file. ```typescript import { langchainConfig } from "@langchain/eslint"; export default langchainConfig; ``` -------------------------------- ### Existing vs. New Decomposition API Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/docs/SPECIFICATION_PARITY.md Illustrates the unchanged convenience function for decomposition and the new class-based approach with the Strategy Pattern. The `decompose()` function remains functional, while `StrategicDecomposer` offers the new API, both yielding the same `DecompositionResult` type. ```typescript import { decompose } from "ava-langchain-prompt-decomposition"; const result = await decompose("Build and test a module."); ``` ```typescript import { StrategicDecomposer } from "ava-langchain-prompt-decomposition"; const decomposer = new StrategicDecomposer(); const { result } = await decomposer.decompose("Build and test a module."); // result.decomposition is the same DecompositionResult type ``` -------------------------------- ### Basic Keyword Decomposition Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/prompt-decomposition/docs/USAGE_EXAMPLES.md Use StrategicDecomposer without LLM resources for deterministic, keyword-based decomposition. This requires no API keys or external services. ```typescript import { StrategicDecomposer } from "ava-langchain-prompt-decomposition"; const decomposer = new StrategicDecomposer(); const result = await decomposer.decompose( "Build a REST API with authentication and write tests for each endpoint." ); // result.result.strategyId === "keyword" // result.result.decomposition — the standard DecompositionResult // result.result.confidence — calibrated confidence (0–1) // result.selectionReason — why keyword was chosen // result.signals — complexity signals (wordCount, clauseCount, …) console.log(result.result.strategyId); // "keyword" console.log(result.selectionReason); // "Selected keyword (score: 1.00) for …" console.log(result.result.decomposition.actions.length); // ordered action items ``` -------------------------------- ### QMD Provider Adapter Interface Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/docs/rispecs/inquiry-routing/qmd-inquiry-execution.spec.md Defines the contract for adapting QMD providers, including their descriptor and a method to execute queries against them. ```typescript export interface QmdProviderAdapter { readonly descriptor: QmdProviderDescriptor; query(args: QmdMcpQueryArguments): Promise; } ``` -------------------------------- ### Visualize the specification Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/state-machine-spec/README.md Generate Mermaid diagrams or text summaries from the defined specification. ```typescript import { generateMermaid, generateTextSummary, } from "ava-langchain-state-machine-spec"; // Mermaid state diagram const diagram = generateMermaid(spec, { showConditions: true, showActions: true, }); // Plain text summary const summary = generateTextSummary(spec); ``` -------------------------------- ### Manage Importance Units with Relational Strings Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/relational-intelligence/README.md Create, connect, deepen, and store importance units linked to four relational sources: Land, Dream, Code, and Vision. Requires importing relevant functions and types. ```typescript import { createImportanceUnit, ImportanceContext, connectToSource, RelationalSource, deepenUnit, ImportanceStore, } from "ava-langchain-relational-intelligence"; // Create a unit from a liminal insight (1.5x accountability weight) const unit = createImportanceUnit( "The knowledge graph should be alive, not flat", "session_123", ImportanceContext.LIMINAL ); // Connect to relational sources connectToSource(unit, RelationalSource.DREAM, 0.9, "Hypnagogic insight"); connectToSource(unit, RelationalSource.VISION, 0.8, "Core architectural direction"); // Deepen through revisitation (circling strengthens, not replaces) deepenUnit(unit, "The wheel should be the ontological filter"); deepenUnit(unit, "Each quadrant is a flavor of relationship", ImportanceContext.CEREMONIAL); // Store and query const store = new ImportanceStore(); store.add(unit); const mostAccountable = store.getByAccountability(10); const needingAttention = store.getNeedingAttention(5); ``` -------------------------------- ### Run environment tests via Docker Compose Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/environment_tests/README.md Execute specific environment tests by targeting the corresponding service defined in the docker-compose.yml file. ```bash docker compose -f environment_tests/docker-compose.yml run # e.g. for test-exports-esbuild docker compose -f environment_tests/docker-compose.yml run test-exports-esbuild ``` -------------------------------- ### Storytelling Hooks: Create Beat Tracer Source: https://github.com/avadisabelle/ava-langchainjs/blob/main/libs/narrative-tracing/README.md Create a beat tracer using StorytellingHooks to log content, analysis, and enrichment for beats in the storytelling system. ```typescript import { StorytellingHooks } from '@langchain/narrative-tracing/adapters'; const hooks = new StorytellingHooks(handler); // Create beat tracer const tracer = hooks.createBeatTracer('beat_001'); tracer.logContent('The story begins...', { narrativeFunction: 'inciting_incident', emotionalTone: 'wonder', }); tracer.logAnalysis('wonder', 0.9); tracer.logEnrichment('dialogue', ['dialogue_enhancer'], 0.7, 0.85); hooks.finishBeatTracer(tracer); ```