x-llm
v1.1.3
Published
A high-performance OpenAI JSON utility for TypeScript.
Readme
OpenAI JSON Utility
A TypeScript utility for calling OpenAI's Chat Completion API with guaranteed JSON output.
Features
- Guaranteed JSON: Uses
response_format: { type: "json_object" }. - Type Safe: Generic
<T>interface for strong typing of LLM responses. - Easy Configuration: Simple parameters for model, instructions, and prompt.
- Token Usage: Returns detailed token usage and finish reason.
Setup
- Clone or copy the files into your project.
- Install dependencies:
npm install openai dotenv - Create a
.envfile based on.env.exampleand add yourOPENAI_API_KEY.
Usage
import "dotenv/config";
import { callOpenAI } from "./callOpenAI.js";
const result = await callOpenAI<{ sentiment: string; score: number }>({
model: "gpt-5-nano",
instructions: "You are a sentiment analyzer. Always respond in JSON with keys: sentiment, score.",
prompt: "Analyze: 'I absolutely love this product!'",
});
console.log(result.data.sentiment); // "positive"AI Functions
matchLists
Intelligently matches items from two lists based on naming and context.
import { matchLists } from "x-llm";
const source = [{ id: 1, name: "Apple" }];
const target = [{ item: "Apple", type: "Fruit" }];
const result = await matchLists({
list1: source,
list2: target,
guidance: "Match by name",
});
console.log(result.matches);
// [{ source: { id: 1, name: "Apple" }, target: { item: "Apple", ... }, reason: "..." }][!TIP] Flexible Schema: The structure of objects in your lists does not matter. The AI uses semantic similarity across all available fields to find matches. If your structures are complex or ambiguous, use the
guidanceparameter to provide specific matching rules. By default, the AI ignores arbitrary IDs (like UUIDs or database sequence IDs) unless they explicitly match between lists.
Important Note
When using json_object format, you must include the word "JSON" in your system instructions or user prompt.
