API Reference
Complete API documentation for all Alchemy packages.
@edv4h/alchemy-core
Core types, refiners, material utilities, and transform helpers. Zero runtime dependencies beyond Zod.
Types
MaterialPart
Discriminated union of all material types. Built-in types:
| Type | Key Fields |
|---|---|
TextMaterialPart | { type: "text"; text: string } |
ImageMaterialPart | { type: "image"; source: { kind: "url"; url } | { kind: "base64"; mediaType; data } } |
AudioMaterialPart | { type: "audio"; source: { kind: "url"; url } | { kind: "base64"; mediaType; data } } |
DocumentMaterialPart | { type: "document"; source: { kind: "url"; url } | { kind: "text"; text; metadata? } } |
VideoMaterialPart | { type: "video"; source: { kind: "url"; url } | { kind: "base64"; mediaType; data } } |
DataMaterialPart | { type: "data"; format: "csv"|"json"|"tsv"; content: string; label?: string } |
MaterialInput
Wire-format for API requests. Same structure as MaterialPart but used for client-to-server communication. Convert with toMaterialParts().
Transmuter
Interface for LLM provider adapters.
interface Transmuter {
transmute(
materials: MaterialPart[],
options: TransmutationOptions,
): Promise<TransmutationResult>;
stream(
materials: MaterialPart[],
options: TransmutationOptions,
): AsyncGenerator<string>;
}
TransmutationOptions
| Property | Type | Description |
|---|---|---|
roleDefinition | string? | System prompt / role definition |
temperature | number? | Sampling temperature (0–2) |
signal | AbortSignal? | Cancellation signal |
language | string? | Output language instruction |
TransmutationResult
| Property | Type | Description |
|---|---|---|
text | string | Raw text output from LLM |
usage | { promptTokens: number; completionTokens: number }? | Token usage |
Refiner<TOutput>
| Property | Type | Description |
|---|---|---|
refine | (raw: string) => TOutput | Parse raw LLM output |
formatInstructions | () => string? | Instructions appended to prompt |
Recipe<TInput, TOutput>
| Property | Type | Description |
|---|---|---|
id | string | Unique recipe identifier |
name | string? | Display name |
spell | (material: TInput) => SpellOutput | Promise<SpellOutput> | Prompt instruction function |
refiner | Refiner<TOutput> | Output parser/validator |
roleDefinition | string? | System prompt / role definition |
temperature | number? | Sampling temperature (0–2) |
transforms | MaterialTransform[]? | Recipe-specific transforms |
requiredMaterials | MaterialRequirement[]? | Declarative material type requirements |
validateMaterials | ((parts: MaterialPart[]) => MaterialValidationResult | Promise<MaterialValidationResult>)? | Custom validation function (sync or async) |
judgeMaterials | ((evaluations: MaterialEvaluationEntry[]) => MaterialJudgement)? | Aggregate quality evaluation to decide transmute eligibility |
Validation
MaterialPartType
Union of all material part type strings: "text" | "image" | "audio" | "document" | "video" | "data"
MaterialRequirement
| Property | Type | Description |
|---|---|---|
type | MaterialPartType | Required material type |
min | number? | Minimum count (default: 1) |
max | number? | Maximum count (undefined = unlimited) |
label | string? | Display label for error messages |
evaluate | ((parts: MaterialPart[]) => MaterialEvaluation | Promise<MaterialEvaluation>)? | Quality scoring function (0–1 score) |
MaterialValidationResult
| Property | Type | Description |
|---|---|---|
valid | boolean | Whether validation passed |
message | string? | Human-readable message |
issues | MaterialValidationIssue[]? | Detailed issue list (type × count check) |
evaluations | MaterialEvaluationEntry[]? | Per-material quality scores |
judgement | MaterialJudgement? | Aggregate transmute eligibility |
MaterialValidationIssue
| Property | Type | Description |
|---|---|---|
type | MaterialPartType | Material type that failed |
label | string? | Label from the requirement |
requirement | { min: number; max?: number } | The requirement that was violated |
actual | number | Actual count of this type |
kind | "too_few" | "too_many" | Type of violation |
MaterialEvaluation
Quality score returned by evaluate on a MaterialRequirement.
| Property | Type | Description |
|---|---|---|
score | number | Quality score between 0 (worst) and 1 (best) |
message | string? | Explanation (e.g. "Response rate is low") |
MaterialEvaluationEntry
Entry passed to judgeMaterials, grouping a requirement's type/label with its evaluation result.
| Property | Type | Description |
|---|---|---|
type | MaterialPartType | Material type |
label | string? | Label from the requirement |
evaluation | MaterialEvaluation | The evaluation result |
MaterialJudgement
Result of judgeMaterials, deciding whether transmutation should proceed.
| Property | Type | Description |
|---|---|---|
canTransmute | boolean | Whether to allow transmutation |
warning | string? | Warning even when canTransmute is true |
message | string? | Reason when canTransmute is false |
validateMaterialRequirements(requirements, parts)
Validate material parts against declarative requirements.
function validateMaterialRequirements(
requirements: MaterialRequirement[],
parts: MaterialPart[],
): MaterialValidationResult;
runMaterialValidation(recipe, parts)
Run the validation pipeline: declarative check → evaluate → judgeMaterials → custom validateMaterials. Each stage runs only when configured, and is skipped if a previous stage fails.
async function runMaterialValidation(
recipe: {
requiredMaterials?: MaterialRequirement[];
validateMaterials?: (parts: MaterialPart[]) => MaterialValidationResult | Promise<MaterialValidationResult>;
judgeMaterials?: (evaluations: MaterialEvaluationEntry[]) => MaterialJudgement;
},
parts: MaterialPart[],
): Promise<MaterialValidationResult>;
Validation stages (each runs only when configured, and is skipped if a previous stage fails):
- Declarative check — validates
requiredMaterialscounts by type (ifrequiredMaterialsis set) - Evaluate — runs each requirement's
evaluate()in parallel, producing quality scores (only for requirements withevaluate) - Judge — passes evaluations to
judgeMaterials()for transmute eligibility (only if evaluations exist andjudgeMaterialsis set) - Custom check — runs
validateMaterials()as a final filter (if provided)
Refiners
TextRefiner
Trims whitespace from the raw output. Returns string.
JsonRefiner<T>
Validates output against a Zod schema.
new JsonRefiner(schema: ZodType<T>)
// Behavior:
// 1. Strips markdown code fences (```json ... ```)
// 2. Parses JSON
// 3. Validates against schema
// 4. Returns typed T
// 5. formatInstructions() returns JSON schema description
Material Utilities
| Function | Description |
|---|---|
normalizeSpellOutput(output) | Converts string/single part to MaterialPart[] |
extractText(parts) | Extracts text parts from materials |
isTextOnly(parts) | Returns true if all parts are text |
extractAllText(parts) | Extracts all extractable text including documents |
toMaterialParts(inputs) | Converts MaterialInput[] to MaterialPart[] |
Transforms
| Function | Description |
|---|---|
truncateText(maxLength) | Truncates text parts to max length |
prependText(text) | Adds text at the beginning of materials |
filterByType(...types) | Keeps only specified material types |
dataToText() | Converts data parts to text representation |
Errors
| Class | Description |
|---|---|
AlchemyError | Base error class |
TransmuteError | LLM API call failure |
RefineError | Output parsing/validation failure |
TransformError | Material transform failure |
MaterialValidationError | Material validation failure (has result: MaterialValidationResult property) |
@edv4h/alchemy-node
Node.js-specific implementations. Depends on @edv4h/alchemy-core and openai.
Alchemist
Main orchestrator class.
Constructor
new Alchemist(config: AlchemistConfig)
interface AlchemistConfig {
transmuter: Transmuter;
transforms?: MaterialTransform[];
validateMaterials?: boolean; // Auto-validate before transmute/stream (default: false)
}
Methods
transmute<TInput, TOutput>(recipe, material, options?)
Execute a recipe with materials and return the parsed output.
| Parameter | Type | Description |
|---|---|---|
recipe | Recipe<TInput, TOutput> | The recipe to execute |
material | TInput | Input material |
options | TransmutationOptions? | Override options (roleDefinition, temperature, language) |
Returns: Promise<TOutput>
stream<TInput>(recipe, material, options?)
Stream the response progressively.
Returns: AsyncGenerator<string>
generate<TInput, TOutput>(recipe, material, count, options?)
Generate multiple variations of the same recipe in parallel.
| Parameter | Type | Description |
|---|---|---|
recipe | Recipe<TInput, TOutput> | The recipe to execute |
material | TInput | Input material |
count | number | Number of variations to generate |
options | TransmutationOptions? | Override options |
Returns: Promise<Record<string, TOutput | { error: Error }>> — Keys are variation-1, variation-2, etc. Uses Promise.allSettled internally.
OpenAITransmuter
OpenAI Chat Completions API transmuter.
new OpenAITransmuter(config?: OpenAITransmuterConfig)
interface OpenAITransmuterConfig {
apiKey?: string; // Defaults to OPENAI_API_KEY env var
defaultModel?: string; // Defaults to "gpt-4o-mini"
baseURL?: string; // Custom API endpoint
}
Material type mapping:
| Material Type | OpenAI Format |
|---|---|
text | Text content |
image | Image URL or base64 |
document | Text content or placeholder |
data | Formatted text with label |
audio / video | Placeholder text |
AnthropicTransmuter
Anthropic Messages API transmuter.
new AnthropicTransmuter(config?: AnthropicTransmuterConfig)
interface AnthropicTransmuterConfig {
apiKey?: string; // Defaults to ANTHROPIC_API_KEY env var
defaultModel?: string; // Defaults to "claude-sonnet-4-20250514"
}
Material type mapping:
| Material Type | Anthropic Format |
|---|---|
text | Text content |
image | Image (base64 or URL) |
document | Text content or placeholder |
data | Formatted text with label |
audio / video | Placeholder text |
GoogleTransmuter
Google Generative AI (Gemini) transmuter.
new GoogleTransmuter(config?: GoogleTransmuterConfig)
interface GoogleTransmuterConfig {
apiKey?: string; // Defaults to GOOGLE_API_KEY env var
defaultModel?: string; // Defaults to "gemini-2.0-flash"
}
Material type mapping:
| Material Type | Google Format |
|---|---|
text | Text part |
image | Inline data (base64) or placeholder |
document | Text content or placeholder |
data | Formatted text with label |
audio / video | Placeholder text |
Node Transforms
| Function | Description |
|---|---|
imageUrlToBase64() | Fetches remote images and converts to base64 |
documentToText() | Extracts text from document parts |
audioToText(options?) | Audio transcription (stub available) |
videoToFrames(options?) | Video frame extraction (stub available) |
@edv4h/alchemy-react
React hooks for building LLM-powered UIs. Peer dependency: react@^18 || ^19.
useTransmute<TOutput>
Low-level hook for single recipe execution.
const {
transmute, // (recipeId, materials, options?) => Promise
data, // TOutput | null
isLoading, // boolean
error, // Error | null
reset, // () => void
} = useTransmute<TOutput>({
baseUrl?: string;
headers?: Record<string, string>;
});
Calls POST /api/transmute/{recipeId} with materials in the body. Supports request cancellation via AbortSignal.
useAlchemy<TOutput>
High-level orchestration hook combining useTransmute and useGenerate with full state management.
const {
// Recipe selection
selectedRecipeId,
selectRecipe,
// Material selection (ID-based)
selectedIds,
toggleMaterial,
clearSelection,
// Language
selectedLanguage,
setLanguage,
// Actions
transmute, // (materials) => Promise
// Results
result, // TOutput | null
isLoading,
error,
resetResults,
} = useAlchemy<TOutput>({
baseUrl?: string;
headers?: Record<string, string>;
initialRecipeId: string;
});
Changing the recipe resets results. Toggling materials resets results but preserves recipe selection.