New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

llmatch-js

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

llmatch-js

A JavaScript library for invoking LLMs and matching their responses with patterns

latest
Source
npmnpm
Version
2025.6.16739
Version published
Maintainers
1
Created
Source

llmatch-js

A JavaScript library for invoking LLMs and matching their responses with patterns. This is a JavaScript port of the Python llmatch package.

Installation

npm install llmatch-js

Features

  • Pattern-matching on LLM responses using regular expressions
  • Automatic retries with exponential backoff
  • Support for any LLM client with a compatible interface
  • Detailed verbose logging option

Usage

Basic Example

const { llmatch } = require('llmatch-js');
import { ChatLLM7 } from "langchain-llm7";

// Initialize your LLM client
const chat = new ChatLLM7()

// Create a wrapper for the LLM that matches the expected interface
const llm = {
  invoke: async (messages, options = {}) => {
    const response = await chat.invoke({
      messages: messages,
      ...options
    });
    
    return {
      content: response.content,
      raw: response
    };
  }
};

// Use llmatch to extract structured data
async function extractJson() {
  const result = await llmatch({
    llm,
    query: "Generate a JSON object with information about a random book.",
    pattern: /```json\n([\s\S]*?)```/,
    verbose: true
  });
  
  if (result.success) {
    // Parse the extracted JSON
    const bookData = JSON.parse(result.extractedData[0]);
    console.log("Book data:", bookData);
  } else {
    console.error("Failed to extract JSON:", result.errorMessage);
  }
}

extractJson().catch(console.error);

API Reference

llmatch(options)

Main function that invokes an LLM and matches the response against a pattern.

ParameterTypeDefaultDescription
llmObjectnullAn already initialized instance of the LLM client
querystring"Extract relevant data."The main query or instruction for the LLM
patternstring | RegExp/(.*?)/sA regex string or compiled RegExp object
contextstringnullOptional additional text to provide context to the LLM
promptTemplatestring"{query}\n\n{context}\nWrite the answer in the next format: {format}"Template string
maxRetriesnumber15Maximum number of attempts to make
initialDelaynumber1.0Seconds to wait before the first retry
backoffFactornumber1.5Multiplier for the delay between retries
verbosebooleanfalseIf true, prints detailed logs of the process
passThroughObject{}Additional parameters to pass to the LLM invocation

Return Value

The function returns a Promise that resolves to an object with the following properties:

PropertyTypeDescription
successbooleanTrue if a valid response was found
extractedDataArray | nullArray of strings matching the pattern (capturing groups), or null if no pattern was provided or matched
finalContentstring | nullThe content of the last successful or final failed LLM response
retriesAttemptednumberNumber of retries made (0 means success on first try)
errorMessagestring | nullDescription of the error if success is false
rawResponseanyThe raw response object from the last LLM call

LLM Interface Requirements

Your LLM client should implement the following interface:

interface LLMClient {
  invoke(messages: Array<{role: string, content: string}>, options?: any): Promise<{
    content: string;
    [key: string]: any;
  }>;
}

License

MIT

Keywords

llm

FAQs

Package last updated on 16 Jun 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts