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

# Validate Prompt

> Validate a Jinja2 system prompt template and receive optimization recommendations

**What it does:** Validate a system prompt written using **Jinja2** template syntax. The endpoint checks whether all template variables and control flow blocks are syntactically correct, extracts all variable names used in the template, and returns a performance analysis with optimization recommendations. Use this endpoint before saving a new system prompt to an agent via **Update Agent**.

## Required Permission

`agents`

## Request Body

| Field | Type | Required | Description |
| - | - | - | - |
| `systemPrompt` | string | Yes\* | The Jinja2 prompt template string to validate. \*Omitting this field or sending `{}` does **not** produce an error — see [Empty Body or Missing `systemPrompt`](#empty-body-or-missing-systemprompt-200) below. |

### Jinja2 Template Syntax

The Platform API uses Jinja2 template syntax for dynamic system prompts. Variables are wrapped in double curly braces:

```
You are a helpful assistant. Customer name is {{ customer_name }}.
```

You can also use control blocks:

```
{% for item in order_items %}
- {{ item.name }}
{% endfor %}
```

At call time, variable values are injected via **Pre-Call Variables** configured on the agent.

## Minimum working example

```bash theme={null}
curl -X POST "https://api.inya.ai/platform/v1/agents/prompt/validate" \
  -H "x-api-key: <your_api_key>" \
  -H "Content-Type: application/json" \
  -d '{
    "systemPrompt": "You are a support agent for {{ company_name }}. The customer is {{ customer_name }}. Today is {{ date }}."
  }'
```

## Response

### Valid Prompt (200)

```json theme={null}
{
  "status": "success",
  "requestId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "message": "Jinja template syntax is valid",
  "response": {
    "isValidTemplate": true,
    "variables": ["company_name", "customer_name", "date"],
    "analysis": {
      "scores": {
        "overall": 85,
        "kvCache": 90,
        "rating": "Good"
      },
      "issues": [],
      "recommendations": []
    }
  }
}
```

### Invalid Prompt (200 with validation error)

```json theme={null}
{
  "status": "success",
  "requestId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "message": "Your prompt is not a valid jinja template. Please check the prompt and try again.",
  "response": {
    "isValidTemplate": false,
    "errors": [
      "Unexpected end of template. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'."
    ],
    "variables": []
  }
}
```

### Empty Body or Missing `systemPrompt` (200)

If the request body is empty (`{}`) or the `systemPrompt` field is absent (e.g. the wrong field name `prompt` is used), the API returns HTTP 200 with `isValidTemplate: true` and empty `variables`. **No error is raised.** Ensure you always send the field named exactly `systemPrompt`.

```json theme={null}
{
  "status": "success",
  "requestId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "message": "Jinja template syntax is valid",
  "response": {
    "isValidTemplate": true,
    "errors": [],
    "variables": [],
    "analysis": {
      "scores": { "overall": 0, "kvCache": 0, "rating": "Unknown" },
      "issues": [],
      "recommendations": []
    }
  }
}
```

> [!WARNING]
>
> Sending an empty body or using the wrong field name (e.g. `prompt` instead of `systemPrompt`) does **not** return an error — the API treats the missing prompt as an empty string and returns `isValidTemplate: true` with no variables extracted. Always verify that `variables` in the response matches your expected template variables to confirm the prompt was received correctly.

## Response Fields

| Field | Type | Description |
| - | - | - |
| `isValidTemplate` | boolean | Whether the prompt is syntactically valid Jinja2. |
| `variables` | string\[] | All template variable names extracted from the prompt (e.g. `"customer_name"`). |
| `errors` | string\[] | Array of syntax error messages (empty when valid). |
| `analysis` | object | Optimization analysis. Only present when `isValidTemplate` is `true`. |
| `analysis.scores.overall` | number | Overall optimization score from 0–100. |
| `analysis.scores.kvCache` | number | KV cache efficiency score from 0–100. Higher scores indicate better LLM cache utilization. |
| `analysis.scores.rating` | string | Human-readable rating: `Poor`, `Fair`, `Good`, or `Excellent`. |
| `analysis.issues` | array | Identified optimization issues. |
| `analysis.recommendations` | array | Suggested improvements to the prompt. |

## Errors

**401 Unauthorized** - Invalid or missing API key

```json theme={null}
{
  "status": "failure",
  "requestId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "message": "Invalid API key"
}
```

**Invalid Jinja syntax is not an HTTP error.** The API returns HTTP `200` with `isValidTemplate: false` and an `errors` array — see [Invalid Prompt (200 with validation error)](#invalid-prompt-200-with-validation-error) above. The same applies to an empty body or a missing `systemPrompt` field.

See [Error Reference](https://docs.gnani.ai/Platform/Error_Reference.md) for other status codes.

## Use Cases

* Validating prompts before saving them to an agent
* Extracting template variable names to configure Pre-Call Variable mappings
* Identifying syntax errors early in the development workflow
* Optimizing prompts for better KV cache performance

> [!NOTE]
>
> A higher `kvCache` score means the LLM can reuse more of its computation across calls, leading to faster response times and lower costs. Move any content that changes per-call (like customer name) towards the end of the prompt to maximize caching.

> [!TIP]
>
> Run this endpoint as part of your CI/CD pipeline to catch prompt template errors before deployment.

> [!NOTE]
>
> Save the `requestId` from every response. You will need it if you contact Gnani support to trace a specific request.


## OpenAPI

````yaml POST /v1/agents/prompt/validate
openapi: 3.0.3
info:
  title: Platform Agents API
  description: API endpoints for creating, managing, and interacting with voice agents
  version: 2.1.0
servers:
  - url: https://api.inya.ai/platform
    description: Production server
security:
  - ApiKeyAuth: []
tags:
  - name: Agents
    description: Agent management operations
  - name: AgentFAQ
    description: Agent FAQ management
  - name: AgentCallTriggers
    description: Outbound call triggers
  - name: ChatSDK
    description: Chat Widget configuration
  - name: Conversations
    description: Conversation logs, statistics, and audio
paths:
  /v1/agents/prompt/validate:
    post:
      tags:
        - Agents
      summary: Validate Jinja2 prompt template
      description: >-
        Validate a Jinja2 system prompt template and extract all template
        variable names.
      operationId: validatePrompt
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - systemPrompt
              properties:
                systemPrompt:
                  type: string
                  description: The Jinja2 prompt template string to validate.
            examples:
              validTemplate:
                value:
                  systemPrompt: Hello {{ customer_name }}, how can I assist?
      responses:
        '200':
          description: Validation result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/StandardResponse'
              examples:
                validPrompt:
                  value:
                    status: success
                    requestId: a1b2c3d4-e5f6-7890-abcd-ef1234567890
                    message: Jinja template syntax is valid
                    response:
                      isValidTemplate: true
                      variables:
                        - customer_name
                      analysis:
                        scores:
                          overall: 85
                          kvCache: 90
                          rating: Good
                        issues: []
                        recommendations: []
        '403':
          $ref: '#/components/responses/Forbidden'
        '500':
          $ref: '#/components/responses/ServerError'
components:
  schemas:
    StandardResponse:
      type: object
      properties:
        status:
          type: string
          example: success
        requestId:
          type: string
          example: a1b2c3d4-e5f6-7890-abcd-ef1234567890
        message:
          type: string
        response:
          type: object
    ErrorResponse:
      type: object
      properties:
        status:
          type: string
          example: failure
        requestId:
          type: string
          example: a1b2c3d4-e5f6-7890-abcd-ef1234567890
        message:
          type: string
  responses:
    Forbidden:
      description: Permission denied
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ServerError:
      description: Internal server error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: x-api-key
      description: API key with 'agents' permission

````

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