Logo
GenerationDraft Generator

Generate Template

Overview

The Generate Template endpoint extracts a structured template from an uploaded document by identifying variables, fields, and placeholders. It analyzes the document to create a fillable form with categories, labels, types, and current values that can be modified to generate new drafts.

Use this endpoint to:

  • Extract structured templates from existing documents
  • Identify variables and fields in contracts, agreements, and forms
  • Create reusable document templates with categorized fields
  • Analyze document structure for automated draft generation
  • Build document automation workflows

Endpoint Details

Method: POST
Endpoint: /api/agent/draft/generate_template
Base URL: https://api.k-v.ai
Authentication: Access Key (Required)


Request Specification

Headers

HeaderTypeRequiredDescription
access-keystringYesYour unique access-key generated from the platform UI
Content-TypestringYesMust be application/json

Request Body

{
    "doc_process_id": "264dfa262b748d15ccbeaada89430c68",
    "model_data": {
        "model_name": "gpt-5.1",
        "api_key": ""
    }
}

Body Fields

FieldTypeRequiredDescription
doc_process_idstringYesDocument ID to extract template from (obtained from Upload or List Documents APIs)
model_dataobjectYesAI model configuration
model_data.model_namestringYesAI model to use for template extraction (see supported models below)
model_data.api_keystringNoYour own LLM API key (leave empty to use platform's default keys)

Supported AI Models

Model NameProvider
gpt-5.1OpenAI
gpt-5-miniOpenAI
claude-sonnet-4-5-20250929Anthropic
gemini/gemini-2.5-flash-liteGoogle
gemini/gemini-2.5-proGoogle
gemini/gemini-3-pro-previewGoogle
mistral/mistral-small-latestMistral AI
mistral/mistral-medium-latestMistral AI
llama3.1-70bMeta

Using Your Own LLM API Keys

Platform Keys (Default)

{
    "model_data": {
        "model_name": "gpt-5.1",
        "api_key": ""
    }
}

Your Own Keys

{
    "model_data": {
        "model_name": "gpt-5.1",
        "api_key": "sk-your-openai-api-key-here"
    }
}

Response Specification

Success Response (200 OK)

{
    "data": {
        "form": [
            {
                "category": "Agreement Basic Information",
                "label": "Governing Law State",
                "type": "text",
                "description": "State whose laws govern the Settlement Agreement",
                "current_value": [
                    "California"
                ],
                "options": null,
                "page_no": null,
                "user_value": null
            },
            {
                "category": "Party Information - Plaintiff",
                "label": "Plaintiff Name",
                "type": "text",
                "description": "Name of the Plaintiff entity",
                "current_value": [
                    "ABC Software Corporation"
                ],
                "options": null,
                "page_no": null,
                "user_value": null
            },
            {
                "category": "Consideration",
                "label": "Settlement Payment Amount",
                "type": "number",
                "description": "Amount Defendant agrees to pay Plaintiff in settlement",
                "current_value": [
                    "one thousand dollars ($1000.00)"
                ],
                "options": null,
                "page_no": null,
                "user_value": null
            }
        ],
        "tokens": {
            "input": 1688,
            "output": 549,
            "total": 2237
        }
    },
    "message": "Draft template generated successfully"
}

Response Fields

FieldTypeDescription
dataobjectResponse data object
data.formarrayArray of template field objects
data.form[].categorystringCategory grouping for the field (e.g., "Party Information", "Recitals")
data.form[].labelstringField label/name
data.form[].typestringField type: text, date, number, etc.
data.form[].descriptionstringDescription of what this field represents
data.form[].current_valuearrayCurrent value(s) extracted from the document
data.form[].optionsarray/nullAvailable options (for dropdown fields), null if not applicable
data.form[].page_nointeger/nullPage number where field was found
data.form[].user_valueany/nullUser-provided value (null in template, to be filled for draft creation)
data.tokensobjectToken usage for template extraction
data.tokens.inputintegerInput tokens consumed
data.tokens.outputintegerOutput tokens generated
data.tokens.totalintegerTotal tokens used
messagestringHuman-readable response message

Error Responses

401 Unauthorized

{
    "data": {},
    "message": "Invalid or missing access key"
}

Cause: Missing or invalid access-key header.


422 Unprocessable Entity - Invalid Model Name

{
    "detail": [
        {
            "type": "literal_error",
            "loc": [
                "body",
                "model_data",
                "model_name"
            ],
            "msg": "Input should be 'gpt-5-chat-latest', 'gpt-5.1', 'gpt-5-mini', 'claude-sonnet-4-5-20250929', 'gemini/gemini-2.5-flash-lite', 'mistral/mistral-small-latest', 'mistral/mistral-medium-latest', 'gemini/gemini-2.5-pro', 'gemini/gemini-3-pro-preview' or 'llama3.1-70b'",
            "input": "",
            "ctx": {
                "expected": "'gpt-5-chat-latest', 'gpt-5.1', 'gpt-5-mini', 'claude-sonnet-4-5-20250929', 'gemini/gemini-2.5-flash-lite', 'mistral/mistral-small-latest', 'mistral/mistral-medium-latest', 'gemini/gemini-2.5-pro', 'gemini/gemini-3-pro-preview' or 'llama3.1-70b'"
            }
        }
    ]
}

Cause: Invalid or unsupported model_name in model_data. See supported models list above.


400 Bad Request - Invalid Document IDs

{
    "data": {},
    "message": "Invalid docs selected"
}

Causes:

  • Missing or invalid doc_process_ids.

500 Internal Server Error - Invalid LLM API Key

{
    "data": {},
    "message": "litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: tyrdfuih**uhf7. You can find your API key at https://platform.openai.com/account/api-keys."
}

Cause: The api_key provided in model_data is invalid or expired. Verify your LLM provider API key.


500 Internal Server Error - General Error

{
    "data": {},
    "message": "Something went wrong"
}

Causes:

  • LLM service temporarily unavailable
  • Server-side processing error

Code Snippets

curl --location 'https://api.k-v.ai/api/agent/draft/generate_template' \
--header 'access-key: YOUR_ACCESS_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "doc_process_id": "264dfa262b748d15ccbeaada89430c68",
    "model_data": {
        "model_name": "gpt-5.1",
        "api_key": ""
    }
}'
import requests
import json

url = "https://api.k-v.ai/api/agent/draft/generate_template"

payload = json.dumps({
    "doc_process_id": "264dfa262b748d15ccbeaada89430c68",
    "model_data": {
        "model_name": "gpt-5.1",
        "api_key": ""
    }
})

headers = {
    'access-key': 'YOUR_ACCESS_KEY',
    'Content-Type': 'application/json'
}

response = requests.post(url, headers=headers, data=payload)

print(response.text)
const axios = require('axios');

let data = JSON.stringify({
    "doc_process_id": "264dfa262b748d15ccbeaada89430c68",
    "model_data": {
        "model_name": "gpt-5.1",
        "api_key": ""
    }
});

let config = {
    method: 'post',
    maxBodyLength: Infinity,
    url: 'https://api.k-v.ai/api/agent/draft/generate_template',
    headers: { 
        'access-key': 'YOUR_ACCESS_KEY',
        'Content-Type': 'application/json'
    },
    data: data
};

axios.request(config)
.then((response) => {
    console.log(JSON.stringify(response.data, null, 2));
})
.catch((error) => {
    console.log(error);
});

Important Notes

  • Document Processing: Only extract templates from documents with status: "processed" from List Documents API
  • Field Categories: Fields are automatically grouped into logical categories for better organization
  • Reusable Templates: Save the template JSON for generating multiple customized drafts
  • user_value Field: Always null in template response; set values when using Create Draft API

Next Steps

After generating a template:

  • Review Extracted Fields: Examine all fields, categories, and current values
  • Save Template: Store the template JSON for reuse
  • Modify Values: Update user_value fields with your custom data
  • Create Draft: Use the Create Draft API with your filled template to generate a document

Need Help? Contact support at support@k-v.ai

On this page