> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Inputs dinâmicos para configuração em tempo de execução

> Passe inputs dinâmicos para prompts de LLM em tempo de execução. Configure variáveis, contexto e parâmetros pelo AI Gateway para uma execução flexível de prompts.

**Casos de uso**

* Personalizar prompts com dados específicos do usuário (nome, nível da conta, histórico) em tempo de execução.
* Reutilizar um único template de prompt em vários contextos sem duplicá-lo.
* Separar a lógica do prompt dos dados de tempo de execução para ter um código mais limpo e testável.
* Injetar conteúdo dinâmico (data atual, chunks recuperados) sem concatenação de strings.

***

Substitua variáveis nas mensagens do prompt usando a sintaxe `{{variableName}}` para injetar conteúdo dinâmico.

## Início rápido

```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://router.toqan.ai/eu/v3/router/responses \
  -H "Authorization: Bearer $TOQAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.6-sol",
    "input": "Hello {{customer_name}}, your {{product_name}} subscription expires soon.",
    "variables": {
      "customer_name": "John Smith",
      "product_name": "Premium Plan"
    }
  }'
```

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.responses.create({
  model: "openai/gpt-5.6-sol",
  input: "Hello {{customer_name}}, your {{product_name}} subscription expires soon.",
  variables: {
    customer_name: "John Smith",
    product_name: "Premium Plan",
  },
});

console.log(response.output_text);
```

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

response = client.responses.create(
    model="openai/gpt-5.6-sol",
    input="Hello {{customer_name}}, your {{product_name}} subscription expires soon.",
    extra_body={
        "variables": {
            "customer_name": "John Smith",
            "product_name": "Premium Plan",
        }
    },
)

print(response.output_text)
```

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.chat.completions.create({
  model: "openai/gpt-5.6-sol",
  messages: [{
    role: "user",
    content: "Hello {{customer_name}}, your {{product_name}} subscription expires soon.",
  }],
  variables: {
    customer_name: "John Smith",
    product_name: "Premium Plan",
  },
});
```

**Resultado**: `"Hello John Smith, your Premium Plan subscription expires soon."`

## Configuração

| Parâmetro | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `variables` | object | Não | Pares chave-valor para substituir as variáveis `{{key}}` nas mensagens |

**Formato das variáveis**: `{{variableName}}` (diferencia maiúsculas de minúsculas, caracteres alfanuméricos + sublinhado)

## Casos de uso

| Cenário | Variáveis | Exemplo de input |
| - | - | - |
| **Suporte ao cliente** | `{{customer_name}}`, `{{issue_type}}` | `{customer_name: "Alice", issue_type: "billing"}` |
| **Recomendações de produtos** | `{{user_preferences}}`, `{{budget}}` | `{user_preferences: "eco-friendly", budget: "$500"}` |
| **Onboarding** | `{{user_name}}`, `{{plan_type}}` | `{user_name: "Bob", plan_type: "Enterprise"}` |
| **Geração de conteúdo** | `{{topic}}`, `{{audience}}` | `{topic: "AI trends", audience: "developers"}` |

## Exemplos de implementação

### Automação de suporte ao cliente

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const supportTicket = {
  customerName: "Sarah Johnson",
  issueType: "billing",
  accountType: "premium",
  ticketId: "TICKET-001"
};

const response = await client.chat.completions.create({
  model: "openai/gpt-5.6-sol",
  messages: [{
    role: "system",
    content: "You are a helpful customer support agent for {{company_name}}."
  }, {
    role: "user",
    content: "Hi, I'm {{customer_name}} and I have a {{issue_type}} issue with my {{account_type}} account. Ticket: {{ticket_id}}"
  }],
  variables: {
    company_name: "Acme Corp",
    customer_name: supportTicket.customerName,
    issue_type: supportTicket.issueType,
    account_type: supportTicket.accountType,
    ticket_id: supportTicket.ticketId
  },
});
```

### Geração de e-mails personalizados

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const emailTemplate = {
  recipient: "Marketing Team",
  campaign: "Q4 Product Launch",
  metrics: "25% increase in engagement"
};

const response = await client.chat.completions.create({
  model: "openai/gpt-5.6-sol",
  messages: [{
    role: "user",
    content: `Create a performance report email for {{recipient}} about the {{campaign}} campaign.
    Highlight that we achieved {{metrics}} and include actionable next steps.`
  }],
  variables: {
    recipient: emailTemplate.recipient,
    campaign: emailTemplate.campaign,
    metrics: emailTemplate.metrics
  },
});
```

### Suporte a vários idiomas

```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://router.toqan.ai/eu/v3/router/responses \
  -H "Authorization: Bearer $TOQAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.6-sol",
    "input": "Generate a {{content_type}} about {{topic}} for {{target_audience}}",
    "variables": {
      "content_type": "blog post",
      "topic": "sustainable technology",
      "target_audience": "enterprise decision makers"
    }
  }'
```

```bash cURL (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST https://router.toqan.ai/eu/v3/router/chat/completions \
  -H "Authorization: Bearer $TOQAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.6-sol",
    "messages": [{
      "role": "user",
      "content": "Generate a {{content_type}} about {{topic}} for {{target_audience}}"
    }],
    "variables": {
      "content_type": "blog post",
      "topic": "sustainable technology",
      "target_audience": "enterprise decision makers"
    }
  }'
```

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const response = await client.responses.create({
  model: "openai/gpt-5.6-sol",
  input: "Generate a {{content_type}} about {{topic}} for {{target_audience}}",
  variables: {
    content_type: "blog post",
    topic: "sustainable technology",
    target_audience: "enterprise decision makers",
  },
});

console.log(response.output_text);
```

```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get("TOQAN_API_KEY"),
    base_url="https://router.toqan.ai/eu/v3/router",
)

response = client.responses.create(
    model="openai/gpt-5.6-sol",
    input="Generate a {{content_type}} about {{topic}} for {{target_audience}}",
    extra_body={
        "variables": {
            "content_type": "blog post",
            "topic": "sustainable technology",
            "target_audience": "enterprise decision makers",
        }
    },
)

print(response.output_text)
```

## Padrões avançados

### Carregamento dinâmico de templates

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

interface TemplateConfig {
  template: string;
  requiredInputs: string[];
  defaultInputs?: Record<string, string>;
}

const templates: Record<string, TemplateConfig> = {
  welcome: {
    template: "Welcome {{user_name}}! Your {{plan_type}} account is now active.",
    requiredInputs: ["user_name", "plan_type"]
  },
  reminder: {
    template: "Hi {{user_name}}, your {{service}} subscription expires in {{days}} days.",
    requiredInputs: ["user_name", "service", "days"],
    defaultInputs: { service: "Premium Plan" }
  }
};

async function generateFromTemplate(
  templateKey: string,
  inputs: Record<string, string>
) {
  const template = templates[templateKey];

  if (!template) {
    throw new Error(`Template ${templateKey} not found`);
  }

  // Validate required inputs
  const missing = template.requiredInputs.filter(key => !inputs[key]);
  if (missing.length > 0) {
    throw new Error(`Missing required inputs: ${missing.join(", ")}`);
  }

  // Merge with defaults
  const finalInputs = { ...template.defaultInputs, ...inputs };

  return await client.chat.completions.create({
    model: "openai/gpt-5.6-sol",
    messages: [{
      role: "user",
      content: template.template
    }],
    variables: finalInputs,
  });
}

// Usage
const response = await generateFromTemplate("welcome", {
  user_name: "Alice Johnson",
  plan_type: "Enterprise"
});
```

### Geração condicional de conteúdo

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

// Generate content based on user tier
const generateTieredContent = async (userTier, baseContent, inputs) => {
  const tierSpecificPrompts = {
    free: "Keep the response brief and mention premium features are available.",
    premium: "Provide detailed information and include premium tips.",
    enterprise: "Include advanced strategies and enterprise-specific recommendations."
  };

  const enhancedInputs = {
    ...inputs,
    user_tier: userTier,
    tier_instruction: tierSpecificPrompts[userTier]
  };

  return await client.chat.completions.create({
    model: "openai/gpt-5.6-sol",
    messages: [{
      role: "system",
      content: "{{tier_instruction}}"
    }, {
      role: "user",
      content: baseContent
    }],
    variables: enhancedInputs,
  });
};
```

### Processamento de inputs em lote

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const batchInputs = [
  { customer_name: "John Doe", product: "Analytics Pro", status: "trial_ending" },
  { customer_name: "Jane Smith", product: "CRM Plus", status: "payment_failed" },
  { customer_name: "Bob Wilson", product: "Marketing Suite", status: "renewal_due" }
];

const template = "Hi {{customer_name}}, your {{product}} account has status: {{status}}. Please take action.";

const responses = await Promise.all(
  batchInputs.map(async (inputs) => {
    return client.chat.completions.create({
      model: "openai/gpt-5.6-sol",
      messages: [{ role: "user", content: template }],
      variables: inputs,
    });
  })
);
```

## Validação de inputs

### Segurança de tipos com TypeScript

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
interface EmailInputs {
  recipient_name: string;
  company_name: string;
  meeting_date: string;
  meeting_time: string;
}

interface ProductInputs {
  product_name: string;
  price: string;
  features: string;
  target_audience: string;
}

function validateInputs<T>(inputs: T, required: (keyof T)[]): void {
  const missing = required.filter(key => !inputs[key]);
  if (missing.length > 0) {
    throw new Error(`Missing required inputs: ${missing.join(", ")}`);
  }
}

// Usage
const emailInputs: EmailInputs = {
  recipient_name: "John Smith",
  company_name: "Acme Inc",
  meeting_date: "December 15",
  meeting_time: "2:00 PM"
};

validateInputs(emailInputs, ["recipient_name", "company_name", "meeting_date"]);
```

### Validação em tempo de execução

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Validate input format and constraints
function validateInputValue(key, value) {
  const validators = {
    email: (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),
    phone: (v) => /^\+?[\d\s-()]+$/.test(v),
    date: (v) => !isNaN(Date.parse(v)),
    price: (v) => /^\$?\d+(\.\d{2})?$/.test(v),
    name: (v) => v.length >= 2 && v.length <= 50
  };

  const validator = validators[key];
  if (validator && !validator(value)) {
    throw new Error(`Invalid ${key} format: ${value}`);
  }
}

// Sanitize inputs
function sanitizeInputs(inputs) {
  const sanitized = {};

  for (const [key, value] of Object.entries(inputs)) {
    // Remove HTML tags and trim whitespace
    const cleanValue = String(value)
      .replace(/<[^>]*>/g, '')
      .trim()
      .substring(0, 1000); // Limit length

    validateInputValue(key, cleanValue);
    sanitized[key] = cleanValue;
  }

  return sanitized;
}
```

## Tratamento de erros

### Detecção de variáveis do template

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Extract variables from template
function extractVariables(template) {
  const matches = template.match(/\{\{([^}]+)\}\}/g) || [];
  return matches.map(match => match.slice(2, -2).trim());
}

// Validate all variables have inputs
function validateTemplate(template, inputs) {
  const variables = extractVariables(template);
  const missing = variables.filter(variable => !inputs.hasOwnProperty(variable));

  if (missing.length > 0) {
    throw new Error(`Missing inputs for variables: ${missing.join(", ")}`);
  }

  return true;
}

// Usage
const template = "Hello {{name}}, your {{product}} expires on {{date}}";
const inputs = { name: "John", product: "Premium Plan" }; // Missing 'date'

try {
  validateTemplate(template, inputs);
} catch (error) {
  console.error(error.message); // "Missing inputs for variables: date"
}
```

### Substituição segura de inputs

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Preview substitution without making API call
function previewSubstitution(template, inputs) {
  let result = template;

  // Replace known variables
  for (const [key, value] of Object.entries(inputs)) {
    const regex = new RegExp(`\\{\\{${key}\\}\\}`, 'g');
    result = result.replace(regex, value);
  }

  // Highlight missing variables
  const remaining = result.match(/\{\{[^}]+\}\}/g) || [];

  return {
    preview: result,
    missingVariables: remaining.map(v => v.slice(2, -2)),
    isComplete: remaining.length === 0
  };
}

// Usage
const preview = previewSubstitution(
  "Hi {{name}}, your {{product}} status is {{status}}",
  { name: "Alice", product: "Pro Plan" }
);

console.log(preview.preview); // "Hi Alice, your Pro Plan status is {{status}}"
console.log(preview.missingVariables); // ["status"]
console.log(preview.isComplete); // false
```

## Otimização de desempenho

### Cache de inputs

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Cache frequently used input combinations
const inputCache = new Map();

function getCachedInputs(cacheKey, inputGenerator) {
  if (inputCache.has(cacheKey)) {
    return inputCache.get(cacheKey);
  }

  const inputs = inputGenerator();
  inputCache.set(cacheKey, inputs);

  // Auto-expire cache entries
  setTimeout(() => inputCache.delete(cacheKey), 5 * 60 * 1000); // 5 minutes

  return inputs;
}

// Usage
const userId = "user-123";
const user = { name: "Alice", subscription: { tier: "pro" }, lastLogin: new Date() };

const userInputs = getCachedInputs(`user-${userId}`, () => ({
  user_name: user.name,
  user_tier: user.subscription.tier,
  last_login: user.lastLogin.toDateString()
}));
```

### Compilação de templates

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

function extractVariables(template) {
  const matches = template.match(/\{\{([^}]+)\}\}/g) || [];
  return matches.map(match => match.slice(2, -2).trim());
}

function validateTemplate(template, inputs) {
  const variables = extractVariables(template);
  const missing = variables.filter(v => !Object.prototype.hasOwnProperty.call(inputs, v));
  if (missing.length > 0) {
    throw new Error(`Missing inputs for variables: ${missing.join(", ")}`);
  }
  return true;
}

// Pre-compile templates for better performance
class TemplateCompiler {
  constructor() {
    this.compiledTemplates = new Map();
  }

  compile(templateId, template) {
    const variables = extractVariables(template);
    this.compiledTemplates.set(templateId, {
      template,
      variables,
      requiredInputs: variables
    });
  }

  async execute(templateId, inputs, model = "openai/gpt-5.6-sol") {
    const compiled = this.compiledTemplates.get(templateId);
    if (!compiled) {
      throw new Error(`Template ${templateId} not found`);
    }

    validateTemplate(compiled.template, inputs);

    return await client.chat.completions.create({
      model,
      messages: [{ role: "user", content: compiled.template }],
      variables: inputs,
    });
  }
}

// Usage
const compiler = new TemplateCompiler();
compiler.compile("welcome", "Welcome {{user_name}} to {{service_name}}!");

const response = await compiler.execute("welcome", {
  user_name: "John",
  service_name: "AI Assistant"
});
```

## Boas práticas

1. **Nomes de variáveis**: use nomes de variáveis descritivos, em snake\_case
2. **Validação de inputs**: sempre valide os inputs antes de enviar requisições
3. **Testes de templates**: teste os templates com dados de exemplo antes de ir para produção
4. **Segurança**: sanitize os inputs do usuário para evitar ataques de injeção
5. **Desempenho**: armazene em cache as combinações de inputs usadas com frequência
6. **Documentação**: documente os inputs obrigatórios de cada template

## Solução de problemas

**Variáveis não substituídas**

* **Causa:** erro de digitação no nome ou na sintaxe da variável.
* **Solução:** verifique se o formato `{{variableName}}` corresponde às chaves dos inputs.

**Conteúdo ausente**

* **Causa:** inputs obrigatórios não foram fornecidos.
* **Solução:** valide se todas as variáveis do template têm inputs correspondentes.

**Saída inesperada**

* **Causa:** HTML ou caracteres especiais nos inputs.
* **Solução:** sanitize os inputs antes de enviar.

**Problemas de desempenho**

* **Causa:** objetos de input grandes.
* **Solução:** limite o tamanho dos inputs e armazene em cache os valores usados com frequência.

## Limitações

| Limitação | Descrição | Alternativa |
| - | - | - |
| **Sintaxe de variáveis** | Apenas o formato `{{variableName}}` é aceito | Use uma convenção de nomes consistente |
| **Objetos aninhados** | Sem suporte à sintaxe `{{user.name}}` | Achate a estrutura do objeto |
| **Tamanho dos inputs** | Inputs grandes aumentam o uso de tokens | Mantenha os inputs concisos e relevantes |
| **Caracteres especiais** | Alguns caracteres podem precisar de escape | Sanitize os inputs adequadamente |
| **Diferenciação de maiúsculas e minúsculas** | Nomes de variáveis diferenciam maiúsculas de minúsculas | Use a mesma capitalização em todo o código |

## Exemplos de integração

### Integração com CMS

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const getCmsClient = () => ({ getTemplate: async (id: string) => ({ template: "Announcing {{product_name}}..." }) }); // replace with your CMS client

// Integrate with content management systems
const cms = getCmsClient();
const cmsContent = await cms.getTemplate("product-announcement");

const response = await client.chat.completions.create({
  model: "openai/gpt-5.6-sol",
  messages: [{ role: "user", content: cmsContent.template }],
  variables: {
    product_name: "AI Analytics Pro",
    release_date: "January 2024",
    key_features: "Advanced reporting, Real-time insights, Custom dashboards",
    target_audience: "Enterprise customers"
  },
});
```

### Integração com banco de dados

```typescript TypeScript (Chat Completions) theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.TOQAN_API_KEY,
  baseURL: "https://router.toqan.ai/eu/v3/router",
});

const database = { users: { findById: async (id: string) => ({ fullName: "Jane Doe", subscription: { type: "pro" } }) }, templates: { findById: async (id: string) => ({ content: "Hello {{user_name}}" }) } }; // replace with your database client
const getUserUsageStats = async (userId: string) => ({ requests: 0 }); // replace with your stats lookup
const getPersonalizedRecommendations = async (userId: string) => ([]); // replace with your recommendations lookup

// Pull dynamic content from database
async function generatePersonalizedContent(userId, templateId) {
  const [user, template] = await Promise.all([
    database.users.findById(userId),
    database.templates.findById(templateId)
  ]);

  const inputs = {
    user_name: user.fullName,
    account_type: user.subscription.type,
    usage_stats: await getUserUsageStats(userId),
    recommendations: await getPersonalizedRecommendations(userId)
  };

  return await client.chat.completions.create({
    model: "openai/gpt-5.6-sol",
    messages: [{ role: "user", content: template.content }],
    variables: inputs,
  });
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.