docs / Crear tu toolkitBuild your toolkit
Conecta .mini a tu llamada a IA#
Empieza con mini setup: idioma, JSON de muestra, nombre y carpeta. El toolkit contiene contrato, prompts y un flujo Python portátil, sin dependencias externas.
Desde el asistente o por comando#
En mini setup, elige Elegir mi archivo para señalar el código que llama a la IA, o Buscar en mi proyecto para localizarlo. Puedes revisar el cambio propuesto o conectar Python compatible con una copia del original. Si eliges Todavía no tengo un flujo, el kit conserva el comando para retomarlo en README.md y GUIA.md.
Cuando tengas el archivo, también puedes conectarlo con:
mini integrate app.py --bundle .mini --lang es
Localiza llamadas de IA y lecturas JSON. Escribe integration/INTEGRATE.md con las rutas reales y, para código compatible, change.diff. Para aplicarlo, repite el comando con --apply.
La edición automática reconoce una llamada Python síncrona client.chat.completions.create(...), asignada a una variable, seguida de json.loads(response.choices[0].message.content). La respuesta no debe tener otros usos. Conserva cliente, modelo, mensajes y parámetros; elimina response_format, lee el prompt generado y conecta el flujo. Guarda el original en integration/app.py.before y crea un puente junto al archivo.
También reconoce una llamada requests.post(...) o httpx.post(...) cuyo argumento json= es un diccionario de chat con messages y response_format (API compatibles con OpenAI, como DeepSeek). El cambio se limita a esa llamada, que pasa por el puente: la petición JSON se envía sin response_format y con el prompt .mini como último mensaje de sistema, y la aplicación recibe una respuesta con la misma forma cuyo contenido es el JSON validado; usage suma todas las llamadas. Las demás peticiones y los errores HTTP no cambian. Si el proveedor informa finish_reason = "length", se descarta la última línea, se conservan los registros completos y se piden solo los que faltan. Cada ejecución queda en .mini/ultima_ejecucion/: las respuestas del modelo tal como llegaron (respuesta_N.mini), el documento validado (resultado.mini) y la traza (ejecucion.json), que se revisan con mini validate, mini to-json y mini tokens.
Otros SDK, lenguajes, streaming, herramientas o funciones asíncronas reciben una guía para tu IA de código: requieren adaptar el callback o el puente al flujo real.
Con tu proveedor: un callback#
Una función recibe un prompt y devuelve texto. Usa la llamada a IA de tu aplicación, sin forzar salida JSON:
import importlib.util
from pathlib import Path
bundle = Path('.mini').resolve()
spec = importlib.util.spec_from_file_location('my_mini_flow', bundle / 'workflow.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
flow = module.Workflow(bundle, lang='es')
def generate(prompt):
response = client.chat.completions.create(
model=model,
messages=[{'role': 'user', 'content': prompt}],
)
return response.choices[0].message.content
data = flow.run(generate, task, expected_records=20)
# data: los datos JSON-compatible de tu aplicación.
# flow.last_run: respuesta, diagnósticos, corrección y resultado.
task contiene los datos de entrada y la tarea. La clave y la configuración siguen en tu aplicación. El callback se usa para generar y corregir; incluye las instrucciones de negocio necesarias en ambas llamadas.
Qué hace el flujo#
- Lee
prompt.es.mdy lo añade a la tarea. - Obtiene .mini de la IA y lo valida.
- Repair elimina envoltorios, BOM y CRLF seguros.
- Pide al mismo callback las líneas incorrectas; conserva las correctas. Los errores de cabecera o recuento requieren regenerar el documento completo.
- Vuelve a validar y comprueba
expected_recordssi lo indicas. - El parser devuelve JSON sólo si todo es válido.
Por defecto hay como máximo una corrección. max_repairs=0 la desactiva. Si aún falla, lanza WorkflowError; el informe está en error.report y flow.last_run. No inventa datos ni reduce el recuento esperado. La validación comprueba estructura y tipos, no la veracidad de la interpretación de la IA.
Código asíncrono y Node#
En Python, usa await flow.run_async(generate, task, expected_records=20) con tu callback asíncrono.
En Node, importa Workflow de ./.mini/workflow.mjs y llama await new Workflow().run(generate, task, {expectedRecords: 20}). El callback puede usar cualquier SDK. El puente ejecuta el mismo runtime Python generado; necesita Python disponible. Valida, repara, pide una corrección y entrega JSON. lastRun contiene el historial.
Desde otro lenguaje#
Pasa texto por stdin a python .mini/workflow.py -. Código 0: JSON por stdout. Código 1: historial y diagnósticos por stderr. El llamador conecta los reintentos semánticos a su proveedor; este comando sólo repara envoltorios y convierte, sin llamadas a IA.
python .mini/workflow.py response.mini --out result.json --expected-records 20
--history archivo.json guarda el recorrido si lo deseas. Puede contener datos de tu aplicación; no incluye la API key porque el runtime nunca la recibe.
Prueba reproducible#
python examples/flujo-soporte/run.py repite los 20 tickets ilustrativos y su corrección con las herramientas reales. --serve abre el formulario local, con opción de IA real y API key en memoria. Ver el historial.
Si cambian los datos, reconstruye en una carpeta nueva con muestras representativas: mini build muestra.json otra.json --prefix ticket --out .mini-v2 --lang es. No edites el contrato a mano. Una muestra no demuestra reglas que nunca observó.
El perfil generado es mini-domain/1 y usa su propio parser Python. Las bibliotecas base Python/TypeScript siguen SPEC 1.1. Las familias son opcionales. Referencia de dominio.
Connect .mini to your AI call#
Start with mini setup: language, sample JSON, name and directory. The toolkit contains a contract, prompts and a portable Python workflow with no external runtime dependencies.
Wizard or command#
In mini setup, choose Select my file to locate your AI-call code or Search my project to find it. Review the proposed change or connect supported Python with an original backup. I do not have a workflow yet keeps the resume command in README.md and GUIA.md.
Once you have the file, you can also run:
mini integrate app.py --bundle .mini --lang en
Locate AI calls and JSON parsing. The command writes integration/INTEGRATE.md with actual paths and change.diff for compatible code. Repeat with --apply to apply it.
Automatic editing recognizes a synchronous Python client.chat.completions.create(...) assignment followed by json.loads(response.choices[0].message.content). The response must have no other uses. It keeps the client, model, messages and parameters, removes response_format, reads the generated prompt and connects the workflow. A backup is kept in integration/app.py.before; a bridge is created beside the source file.
It also recognizes a requests.post(...) or httpx.post(...) call whose json= argument is a chat dictionary with messages and response_format (OpenAI-compatible APIs such as DeepSeek). Only that call changes and goes through the bridge: the request is sent without response_format, with the .mini prompt as a last system message, and the app receives a response of the same shape whose content is the validated JSON; usage adds up every call. Other requests and HTTP errors are unchanged. When the provider reports finish_reason = "length", the last line is discarded, complete records are kept and only the missing ones are requested. Each run is kept in .mini/last_run/ (.mini/ultima_ejecucion/ in Spanish toolkits): the model answers as received, the validated document and the trace, ready for mini validate, mini to-json and mini tokens.
Other SDKs/languages, streaming, tools and asynchronous functions receive a coding-AI guide and need an application-specific callback or bridge.
Keep your provider with a callback#
A function receives a prompt and returns text. Use your existing AI call without JSON-only output mode:
import importlib.util
from pathlib import Path
bundle = Path('.mini').resolve()
spec = importlib.util.spec_from_file_location('my_mini_flow', bundle / 'workflow.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
flow = module.Workflow(bundle, lang='en')
def generate(prompt):
response = client.chat.completions.create(
model=model,
messages=[{'role': 'user', 'content': prompt}],
)
return response.choices[0].message.content
data = flow.run(generate, task, expected_records=20)
# data: JSON-compatible application data.
# flow.last_run: response, diagnostics, correction and result.
task includes actual inputs and business instructions. Credentials remain in your application. The callback is used for generation and correction; keep necessary business instructions in both calls.
What happens#
- Read prompt.en.md and append it to the task.
- Obtain .mini from AI and validate.
- Repair safe wrappers, BOM and CRLF.
- Ask the same callback to replace invalid lines, preserving valid lines. Header/count errors request a complete regeneration.
- Revalidate and check expected_records when provided.
- Return JSON only on success.
At most one correction is requested by default. max_repairs=0 disables it. Pending errors raise WorkflowError; error.report and flow.last_run expose diagnostics. No invented data or silent count reduction. Validation checks structure/types, not the truth of the AI interpretation.
Async Python and Node#
Use await flow.run_async(generate, task, expected_records=20) with an async Python callback.
In Node, import Workflow from ./.mini/workflow.mjs and call await new Workflow().run(generate, task, {expectedRecords: 20}). The callback keeps any SDK. This bridge runs the same generated Python runtime and requires Python. It validates, repairs, requests a correction and returns JSON. lastRun holds the history.
Other languages#
Pipe text to python .mini/workflow.py -. Exit 0 yields JSON on stdout; exit 1 yields history and diagnostics on stderr. Connect semantic retries in the calling application; the CLI only repairs safe wrappers and parses, without AI calls.
python .mini/workflow.py response.mini --out result.json --expected-records 20
--history file.json optionally saves the run. It may contain application data, but no API key: the runtime never receives credentials.
Reproducible test#
python examples/flujo-soporte/run.py replays the 20 illustrative tickets and correction with the actual tools. --serve opens the local form with optional live AI and an API key held in memory. See the history.
Rebuild in a new directory for changing data: mini build sample.json more.json --prefix ticket --out .mini-v2 --lang en. Do not edit the contract by hand. Samples cannot prove unobserved rules.
The generated mini-domain/1 profile uses its own Python parser. Base Python/TypeScript libraries implement SPEC 1.1. Families are optional. Domain reference.