Methods
All methods accept prompt as the first argument and optional BillyOptions as the second. They return Promise<unknown> and store the result in .results.
.create(prompt, options?)
Generate new content.
await IA.create("Escribe un poema sobre el mar");
await IA.create("Dame 5 preguntas", { temperature: 0.8 });.modify(prompt, options?)
Transform the previous result according to new instructions.
await IA.create("Una casa en el campo");
await IA.modify("Convierte eso en un texto más poético");
// Automatically prepends the previous .results as context.validate(prompt, options?)
Verify or answer questions.
const isValid = await IA.asBoolean().validate(
"¿Este email contiene phishing?"
);.analyze(prompt, options?)
Analyze data and provide insights.
const analysis = await IA.analyze(
"Dame un resumen de estas métricas: ..."
);.extract(prompt, options?)
Extract specific information from text.
const info = await IA.asObject().extract(
"Extrae: nombre, email, teléfono del texto: ..."
);.execute(prompt, options?)
Execute a calculation and return the result.
const result = await IA.asNumber().execute("Cuánto es 15 * 7");
console.log(result); // 105.schema(def)
Define a structured schema that the response must match. Chainable. Automatically validates and retries if the LLM response doesn't fit.
const user = await IA
.schema({
name: "string",
age: "number",
active: "boolean",
})
.create("Dame un usuario ficticio");
console.log(user);
// → { name: "Ana", age: 28, active: true }Supported types in schemas
| Schema type | JS type | Example |
|---|---|---|
"string" | string | "Juan" |
"number" | number | 42 |
"boolean" | boolean | true |
["string"] | string[] | ["a", "b"] |
["number"] | number[] | [1, 2] |
{ ... } | Nested object | { city: "string" } |
Nested schemas
const result = await IA
.schema({
title: "string",
tags: ["string"],
author: {
name: "string",
age: "number",
},
})
.create("Dame un post con autor");Automatic retry on validation failure
If the LLM returns something that doesn't match the schema, billy-sdk automatically retries with the validation errors as feedback.
.stream(prompt, options?)
Stream the response chunk by chunk in real time. Returns an AsyncIterable<string>.
const stream = IA.stream("Escribe un cuento corto");
for await (const chunk of stream) {
process.stdout.write(chunk); // aparece en tiempo real
}
console.log(IA.results); // resultado completo al finalizarAccepts { type, temperature, maxTokens, signal, files } options:
// Stream with a different task type
const stream = IA.stream("Hola mundo", { type: "extract" });
// Or combined with chaining
const stream = IA.asObject()
.schema({ titulo: "string", contenido: "string" })
.stream("Dame un cuento estructurado");
for await (const chunk of stream) {
process.stdout.write(chunk);
}
console.log(IA.results); // objeto validadoNote: Schema validation runs after all chunks arrive, not per-chunk.
📄 examples/streaming.mjs
Options (second argument)
All task methods and .stream() accept an optional BillyOptions object:
| Option | Type | Description |
|---|---|---|
type | "create" | "modify" | "validate" | "analyze" | "extract" | "execute" | Override task type (defaults to method name) |
temperature | number | Per-request temperature override |
maxTokens | number | Per-request max tokens override |
signal | AbortSignal | Abort signal for cancellation |
files | FileContent[] | Attach images, PDFs, or text files |
await IA.create("prompt", { temperature: 0.9, maxTokens: 200 });
const ac = new AbortController();
const stream = IA.stream("long text", { signal: ac.signal });
// later: ac.abort()File attachments
Pass files inline or via chaining:
// Via options
await IA.create("Describe esta imagen", {
files: [{ type: "image", path: "./foto.jpg" }]
});
// Via chaining (recommended)
await IA.withPdf("./informe.pdf").extract("Resume este documento");
await IA.withImageUrl("https://ejemplo.com/img.jpg").create("Qué ves?");For type/length coercion, use chaining instead:
await IA.asNumber().short().create("5 * 3"); // ✓.system(prompt)
Set a system prompt to define the AI's role, behavior, or constraints. Chainable.
IA.system("Eres un experto en historia medieval");
const respuesta = await IA.create("Háblame sobre el feudalismo");The system prompt can be combined with any method and type:
const criticas = await IA
.system("Eres un crítico de cine sarcástico")
.asArray()
.create("Dame 3 reseñas de películas de terror");You can also set it in the initial configuration:
const IA = billy({ systemPrompt: "Eres un asistente amigable" });Memory (Conversation History)
Enable automatic memory when creating the instance:
const IA = billy({ memory: 10 }); // remember last 10 turns
await IA.create("Hola, me llamo Juan");
await IA.create("¿Cómo me llamo?"); // sabe que te llamas JuanMemory stores user messages and assistant responses. Each create() / modify() / etc. call adds one turn.
TTL (Time To Live)
const IA = billy({ memory: 10, memoryTtl: 60000 }); // expira después de 60sMethods
| Method | Description |
|---|---|
IA.withMemory(n, ttl?) | Enable memory mid-flight (chainable) |
IA.clearMemory() | Reset conversation history |
IA.memory | Get current history (read-only array) |
Properties
After any method call, these properties are available:
| Property | Type | Description |
|---|---|---|
.results | unknown | Last result (parsed) |
.raw | string | Raw response from AI |
.error | string | undefined | Error message if failed |