@hardlydifficult/ai-msg
v1.0.4
Published
Extract structured data from AI model responses: JSON, typed schemas, code blocks, and multimodal content.
Readme
@hardlydifficult/ai-msg
Extract structured data from AI model responses: JSON, typed schemas, code blocks, and multimodal content.
Installation
npm install @hardlydifficult/ai-msgAPI
extractJson(text: string, sentinel?: string): unknown[]
Extract JSON objects/arrays from AI response text. Uses a three-pass strategy:
- Parse the entire text as JSON
- Extract from fenced code blocks (json-tagged first, then any)
- Find balanced
{}/[]in prose
Pass a sentinel string to return [] when the response contains it (useful for "no results" markers).
import { extractJson } from "@hardlydifficult/ai-msg";
extractJson('Here is the result:\n```json\n{"key": "value"}\n```\nDone.');
// [{ key: "value" }]
extractJson('First {"a": 1} then {"b": 2} done.');
// [{ a: 1 }, { b: 2 }]
extractJson("NO_FINDINGS: scan completed.", "NO_FINDINGS");
// []extractTyped<T>(text: string, schema: SchemaLike<T>, sentinel?: string): T[]
Extract and validate JSON against a schema. Works with Zod 3, Zod 4, or any object with a safeParse method. Only returns entries that pass validation.
import { extractTyped } from "@hardlydifficult/ai-msg";
import { z } from "zod";
const Person = z.object({ name: z.string(), age: z.number() });
extractTyped('{"name": "Alice", "age": 30}', Person);
// [{ name: "Alice", age: 30 }]
extractTyped('{"name": "Alice", "age": "thirty"}', Person);
// [] — fails validationextractCodeBlock(text: string, lang?: string): string[]
Extract fenced code block contents. Optionally filter by language tag.
import { extractCodeBlock } from "@hardlydifficult/ai-msg";
extractCodeBlock("```ts\nconst x = 1;\n```");
// ["const x = 1;"]
extractCodeBlock("```json\n{}\n```\n```ts\nconst x = 1;\n```", "json");
// ["{}"]extractTextContent(content: string | { type: string; text?: string }[]): string
Extract plain text from a message content field. Handles both plain strings and multimodal content arrays (AI SDK format).
import { extractTextContent } from "@hardlydifficult/ai-msg";
extractTextContent("hello"); // "hello"
extractTextContent([
{ type: "text", text: "hello" },
{ type: "image_url", url: "..." },
]); // "hello"toPlainTextMessages(messages: MultimodalMessage[]): { role, content }[]
Convert multimodal messages to plain text messages by flattening content arrays.
