Uma super estrutura para engenharia imediata.
Uma estrutura baseada em XML para definir, gerenciar e validar prompts de AI/LLM de forma estruturada.
Ele traz princípios de engenharia de software para a engenharia imediata, fornecendo um sistema robusto para manipulação de variáveis, lógica condicional e design modular de prompts.
Esteja você criando aplicativos complexos de IA ou gerenciando uma biblioteca de prompts, o One Prompt ajuda a garantir consistência, capacidade de manutenção e confiabilidade em seu fluxo de trabalho de engenharia de prompts.
# Using npm
npm install oneprompt
# Using yarn
yarn add oneprompt
# Using pnpm
pnpm add oneprompt
# Using bun
bun add oneprompt
<!-- Basic metadata about the prompt -->
< metadata >
< title >Support Request</ title >
</ metadata >
<!-- Variable definitions with required/optional flags -->
< variables >
< var name = " issue_category " required = " true " />
</ variables >
<!-- Main template with conditional logic and variable placeholders -->
< template >
Thank you for contacting support regarding your {{issue_category}} issue.
Our team strives to provide timely and effective solutions. Here's what you can expect:
< oneprompt : if var = " issue_category " equals = " billing " show = " billing_info " />
We'll be in touch within 24-48 hours with a detailed response.
Best regards,
Support Team
</ template >
<!-- Reusable content parts referenced by conditionals -->
< part name = " billing_info " >
For billing-related inquiries, please have your latest invoice and account number ready.
</ part >
import { OnePrompt } from 'oneprompt' ;
const prompt = ... ; // your XML prompt or prompt object
const rendered = OnePrompt . renderWithVariables ( prompt , {
name : "John" ,
style : "casual"
} ) ;
// Output: "Hey John!"
A seção de metadados define informações sobre o próprio prompt:
< metadata >
< title >Customer Response</ title >
< description >Template for customer inquiries</ description >
< team >Support</ team >
</ metadata >
Variáveis são espaços reservados que são substituídos por valores reais. Eles podem ser:
< variables >
< var name = " customer_name " required = " true " />
< var name = " priority " required = " false " >normal</ var >
< var name = " response_type " required = " false " >standard</ var >
</ variables >
O conteúdo principal com espaços reservados para variáveis e lógica condicional:
< template >
Dear {{customer_name}},
< oneprompt : if var = " priority " equals = " high " show = " urgent_response " else = " standard_response " />
Best regards,
Support Team
</ template >
Blocos de conteúdo reutilizáveis que podem ser referenciados em condicionais:
< part name = " urgent_response " >
We have marked your case as high priority and assigned a dedicated specialist...
</ part >
< part name = " standard_response " >
Thank you for your inquiry. We will process your request...
</ part >
parseFromXml(xml: string): Prompt
Analisa uma string XML em um objeto Prompt validado.
// Basic usage
const xml = `
<metadata>
<title>Customer Greeting</title>
</metadata>
<variables>
<var name="name" required="true" />
<var name="language" required="false">english</var>
</variables>
<template>
<oneprompt:if var="language" equals="spanish" show="spanish_greeting" else="english_greeting" />
{{name}}!
</template>
<part name="spanish_greeting">¡Hola</part>
<part name="english_greeting">Hello</part>
` ;
try {
const prompt = OnePrompt . parseFromXml ( xml ) ;
console . log ( prompt ) ;
// {
// metadata: { title: "Customer Greeting" },
// variables: [
// { name: "name", required: true },
// { name: "language", required: false, default: "english" }
// ],
// template: "...",
// parts: [...]
// }
} catch ( error ) {
if ( error instanceof OnePromptError ) {
console . error ( "Invalid prompt XML:" , error . message ) ;
}
}
convertToXml(prompt: Prompt): string
Converte um objeto Prompt de volta para o formato XML.
const prompt : Prompt = {
metadata : {
title : "Meeting Request" ,
author : "Support Team"
} ,
variables : [
{ name : "requester" , required : true } ,
{ name : "time" , required : false , default : "tomorrow" }
] ,
template : "Meeting requested by {{requester}} for {{time}}" ,
parts : [ ]
} ;
try {
const xml = OnePrompt . convertToXml ( prompt ) ;
console . log ( xml ) ;
// <metadata>
// <title>Meeting Request</title>
// <author>Support Team</author>
// </metadata>
// <variables>
// <var name="requester" required="true" />
// <var name="time" required="false">tomorrow</var>
// </variables>
// <template>Meeting requested by {{requester}} for {{time}}</template>
} catch ( error ) {
console . error ( "Conversion failed:" , error . message ) ;
}
validate(prompt: Prompt): void
Valida a estrutura e os relacionamentos de um prompt.
const prompt : Prompt = {
metadata : { title : "Email Template" } ,
variables : [
{ name : "recipient" , required : true } ,
{ name : "tone" , required : false , default : "formal" }
] ,
template : `
<oneprompt:if var="tone" equals="formal" show="formal_greeting" else="casual_greeting" />
{{recipient}},
{{message}} // This will cause validation error - 'message' not defined
` ,
parts : [
{ name : "formal_greeting" , content : "Dear" } ,
{ name : "casual_greeting" , content : "Hi" }
]
} ;
try {
OnePrompt . validate ( prompt ) ;
} catch ( error ) {
if ( error instanceof OnePromptError ) {
// Error: "Variable 'message' used in template but not declared"
console . error ( error . message ) ;
}
}
renderWithVariables(source: string | Prompt, variables: PromptInputVariables): string
Processa um prompt com variáveis fornecidas para criar a saída final.
// Using prompt object
const prompt : Prompt = {
metadata : { title : "Support Response" } ,
variables : [
{ name : "ticket_id" , required : true } ,
{ name : "priority" , required : false , default : "normal" }
] ,
template : `
Ticket #{{ticket_id}}
<oneprompt:if var="priority" equals="high" show="urgent_notice" />
` ,
parts : [
{ name : "urgent_notice" , content : "URGENT: Requires immediate attention" }
]
} ;
// Success case
try {
const output1 = OnePrompt . renderWithVariables ( prompt , {
ticket_id : "T-123" ,
priority : "high"
} ) ;
console . log ( output1 ) ;
// Ticket #T-123
// URGENT: Requires immediate attention
const output2 = OnePrompt . renderWithVariables ( prompt , {
ticket_id : "T-456"
} ) ;
console . log ( output2 ) ;
// Ticket #T-456
// (no urgent notice because priority is "normal" by default)
} catch ( error ) {
console . error ( "Render failed:" , error . message ) ;
}
// Error case - missing required variable
try {
OnePrompt . renderWithVariables ( prompt , {
priority : "high"
// Missing ticket_id
} ) ;
} catch ( error ) {
// Error: "Missing required variable: ticket_id"
console . error ( error . message ) ;
}
extractTemplateVariables(template: string): string[]
Extrai nomes de variáveis de uma string de modelo.
const template = `
Dear {{recipient}},
Your order #{{order_id}} has been {{status}}.
<oneprompt:if var="tracking_number" equals="available" show="tracking_info" />
` ;
const variables = OnePromptUtils . extractTemplateVariables ( template ) ;
console . log ( variables ) ;
// ["recipient", "order_id", "status"]
validateAndProcessVariables(promptVars: PromptVariable[], inputVars: PromptInputVariables): PromptInputVariables
Valida variáveis de entrada em relação às especificações e aplica padrões.
const promptVariables : PromptVariable [ ] = [
{ name : "user" , required : true } ,
{ name : "role" , required : false , default : "viewer" } ,
{ name : "team" , required : false , default : "general" }
] ;
// Success case - with defaults
const processed1 = OnePromptUtils . validateAndProcessVariables (
promptVariables ,
{ user : "john.doe" }
) ;
console . log ( processed1 ) ;
// {
// user: "john.doe",
// role: "viewer",
// team: "general"
// }
// Success case - override defaults
const processed2 = OnePromptUtils . validateAndProcessVariables (
promptVariables ,
{ user : "jane.doe" , role : "admin" , team : "engineering" }
) ;
console . log ( processed2 ) ;
// {
// user: "jane.doe",
// role: "admin",
// team: "engineering"
// }
// Error case - missing required
try {
OnePromptUtils . validateAndProcessVariables (
promptVariables ,
{ role : "admin" } // Missing required 'user'
) ;
} catch ( error ) {
console . error ( error . message ) ; // "Missing required variable: user"
}
substituteTemplateVariables(template: string, variables: PromptInputVariables): string
Substitui espaços reservados de variáveis pelos seus valores.
const template = `
Project: {{project_name}}
Owner: {{owner}}
Status: {{status}}
{{#if has_description}}
Description: {{description}}
{{/if}}
` ;
const result = OnePromptUtils . substituteTemplateVariables (
template ,
{
project_name : "OnePrompt" ,
owner : "DevTeam" ,
status : "Active" ,
// description not provided
}
) ;
console . log ( result ) ;
// Project: OnePrompt
// Owner: DevTeam
// Status: Active
// {{#if has_description}}
// Description: {{description}}
// {{/if}}
processConditionals(template: string, variables: PromptInputVariables, parts: PromptPart[]): string
Processa expressões condicionais e inclui partes apropriadas.
const template = `
<oneprompt:if var="access_level" equals="admin" show="admin_actions" else="user_actions" />
<oneprompt:if var="has_notifications" equals="true" show="notification_panel" />
` ;
const variables = {
access_level : "admin" ,
has_notifications : "true"
} ;
const parts : PromptPart [ ] = [
{
name : "admin_actions" ,
content : "- Create Usern- Delete Usern- Modify Settings"
} ,
{
name : "user_actions" ,
content : "- View Profilen- Update Settings"
} ,
{
name : "notification_panel" ,
content : "You have new notifications!"
}
] ;
const processed = OnePromptUtils . processConditionals (
template ,
variables ,
parts
) ;
console . log ( processed ) ;
// - Create User
// - Delete User
// - Modify Settings
//
// You have new notifications!
À medida que os aplicativos de IA e LLM se tornam mais complexos, o gerenciamento de prompts como sequências simples torna-se cada vez mais sujeito a erros e difícil de manter. Precisávamos de uma maneira de:
A abordagem baseada em XML foi escolhida para fornecer uma estrutura clara, mantendo a legibilidade e permitindo que metadados e regras de validação vivam junto com o próprio modelo de prompt. Isso torna os prompts autodocumentados e permite uma melhor colaboração entre engenheiros, desenvolvedores e outras partes interessadas.
O One Prompt tem como objetivo trazer as melhores práticas de engenharia de software para a engenharia imediata, mantendo a experiência do desenvolvedor simples e intuitiva.
Para bugs e solicitações de recursos, abra um problema.
MIT