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

# Dynamic inputs for runtime configuration

> Pass dynamic inputs to LLM prompts at runtime. Configure variables, context, and parameters through the AI Router for flexible prompt execution.

Replace variables in prompt messages using `{{variableName}}` syntax for dynamic content injection.

## Quick Start

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const response = await openai.chat.completions.create({
    model: "openai/gpt-4o",
    messages: [{
      role: "user",
      content: "Hello {{customer_name}}, your {{product_name}} subscription expires soon."
    }],
    inputs: {
      customer_name: "John Smith",
      product_name: "Premium Plan"
    },
  });
  ```
</CodeGroup>

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

## Configuration

| Parameter | Type   | Required | Description                                                |
| --------- | ------ | -------- | ---------------------------------------------------------- |
| `inputs`  | object | No       | Key-value pairs to replace `{{key}}` variables in messages |

**Variable Format**: `{{variableName}}` (case-sensitive, alphanumeric + underscore)

## Use Cases

| Scenario                    | Variables                             | Example Input                                        |
| --------------------------- | ------------------------------------- | ---------------------------------------------------- |
| **Customer Support**        | `{{customer_name}}`, `{{issue_type}}` | `{customer_name: "Alice", issue_type: "billing"}`    |
| **Product Recommendations** | `{{user_preferences}}`, `{{budget}}`  | `{user_preferences: "eco-friendly", budget: "$500"}` |
| **Onboarding**              | `{{user_name}}`, `{{plan_type}}`      | `{user_name: "Bob", plan_type: "Enterprise"}`        |
| **Content Generation**      | `{{topic}}`, `{{audience}}`           | `{topic: "AI trends", audience: "developers"}`       |

## Implementation Examples

### Customer Support Automation

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const supportTicket = {
    customerName: "Sarah Johnson",
    issueType: "billing",
    accountType: "premium",
    ticketId: "TICKET-001"
  };

  const response = await openai.chat.completions.create({
    model: "openai/gpt-4o",
    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}}"
    }],
    inputs: {
      company_name: "Acme Corp",
      customer_name: supportTicket.customerName,
      issue_type: supportTicket.issueType,
      account_type: supportTicket.accountType,
      ticket_id: supportTicket.ticketId
    },
  });
  ```
</CodeGroup>

### Personalized Email Generation

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const emailTemplate = {
    recipient: "Marketing Team",
    campaign: "Q4 Product Launch",
    metrics: "25% increase in engagement"
  };

  const response = await openai.chat.completions.create({
    model: "openai/gpt-4o",
    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.`
    }],
    inputs: {
      recipient: emailTemplate.recipient,
      campaign: emailTemplate.campaign,
      metrics: emailTemplate.metrics
    },
  });
  ```
</CodeGroup>

### Multi-Language Support

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X POST https://api.orq.ai/v3/router/chat/completions \
    -H "Authorization: Bearer $ORQ_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "openai/gpt-4o",
      "messages": [{
        "role": "user",
        "content": "Generate a {{content_type}} about {{topic}} for {{target_audience}}"
      }],
      "inputs": {
        "content_type": "blog post",
        "topic": "sustainable technology",
        "target_audience": "enterprise decision makers"
      }
    }'
  ```

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

  client = openai.OpenAI(
      api_key=os.environ["ORQ_API_KEY"],
      base_url="https://api.orq.ai/v3/router"
  )

  user_context = {
      "user_name": "María García",
      "language": "español",
      "product": "Plan Premium",
      "expiry_date": "15 de diciembre"
  }

  response = client.chat.completions.create(
      model="openai/gpt-4o",
      messages=[{
          "role": "user",
          "content": "Genera un mensaje en {{language}} para {{user_name}} sobre la renovación de {{product}} que vence el {{expiry_date}}."
      }],
      extra_body={
          "inputs": user_context
      }
  )
  ```
</CodeGroup>

## Advanced Patterns

### Dynamic Template Loading

<CodeGroup>
  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  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 openai.chat.completions.create({
      model: "openai/gpt-4o",
      messages: [{
        role: "user",
        content: template.template
      }],
      inputs: finalInputs,
    });
  }

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

### Conditional Content Generation

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // 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 openai.chat.completions.create({
      model: "openai/gpt-4o",
      messages: [{
        role: "system",
        content: "{{tier_instruction}}"
      }, {
        role: "user",
        content: baseContent
      }],
      inputs: enhancedInputs,
    });
  };
  ```
</CodeGroup>

### Batch Input Processing

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  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 openai.chat.completions.create({
        model: "openai/gpt-4o",
        messages: [{ role: "user", content: template }],
        inputs,
      });
    })
  );
  ```
</CodeGroup>

## Input Validation

### Type Safety with TypeScript

<CodeGroup>
  ```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"]);
  ```
</CodeGroup>

### Runtime Validation

<CodeGroup>
  ```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;
  }
  ```
</CodeGroup>

## Error Handling

### Template Variable Detection

<CodeGroup>
  ```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"
  }
  ```
</CodeGroup>

### Safe Input Substitution

<CodeGroup>
  ```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
  ```
</CodeGroup>

## Performance Optimization

### Input Caching

<CodeGroup>
  ```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 userInputs = getCachedInputs(`user-${userId}`, () => ({
    user_name: user.name,
    user_tier: user.subscription.tier,
    last_login: user.lastLogin.toDateString()
  }));
  ```
</CodeGroup>

### Template Compilation

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // 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-4o") {
      const compiled = this.compiledTemplates.get(templateId);
      if (!compiled) {
        throw new Error(`Template ${templateId} not found`);
      }

      validateTemplate(compiled.template, inputs);

      return await openai.chat.completions.create({
        model,
        messages: [{ role: "user", content: compiled.template }],
        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"
  });
  ```
</CodeGroup>

## Best Practices

1. **Variable Naming**: Use descriptive, snake\_case variable names
2. **Input Validation**: Always validate inputs before sending requests
3. **Template Testing**: Test templates with sample data before production
4. **Security**: Sanitize user inputs to prevent injection attacks
5. **Performance**: Cache frequently used input combinations
6. **Documentation**: Document required inputs for each template

## Troubleshooting

**Variables not replaced**

* **Cause:** Typo in variable name or syntax
* **Solution:** Check `{{variableName}}` format matches input keys

**Missing content**

* **Cause:** Required inputs not provided
* **Solution:** Validate all template variables have corresponding inputs

**Unexpected output**

* **Cause:** HTML/special characters in inputs
* **Solution:** Sanitize inputs before sending

**Performance issues**

* **Cause:** Large input objects
* **Solution:** Limit input size and cache frequently used values

## Limitations

| Limitation             | Description                              | Workaround                       |
| ---------------------- | ---------------------------------------- | -------------------------------- |
| **Variable Syntax**    | Only `{{variableName}}` format supported | Use consistent naming convention |
| **Nested Objects**     | No support for `{{user.name}}` syntax    | Flatten object structure         |
| **Input Size**         | Large inputs increase token usage        | Keep inputs concise and relevant |
| **Special Characters** | Some characters may need escaping        | Sanitize inputs appropriately    |
| **Case Sensitivity**   | Variable names are case-sensitive        | Use consistent casing throughout |

## Integration Examples

### CMS Integration

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // Integrate with content management systems
  const cmsContent = await cms.getTemplate("product-announcement");

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

### Database Integration

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // 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 openai.chat.completions.create({
      model: "openai/gpt-4o",
      messages: [{ role: "user", content: template.content }],
      inputs,
    });
  }
  ```
</CodeGroup>
