Prompts API

Complete API reference for creating, managing, executing, and versioning prompts via GraphQL.

Overview

The Prompts API provides full control over prompt lifecycle management including creation, versioning, execution, forking, and deletion. All operations use GraphQL for type safety and precise data fetching.

All API requests require authentication via API key in the X-API-Key header. See the Authentication guide for details.

Queries

Get All Prompts

query
prompts

Retrieve all prompts for the authenticated user

query GetPrompts {
  prompts {
    id
    name
    description
    category
    isPublic
    createdAt
    updatedAt
    versions {
      id
      version
      content
      params
      createdAt
    }
  }
}

Get Single Prompt

query
prompt

Retrieve a specific prompt by ID with all versions

query GetPrompt($id: ID!) {
  prompt(id: $id) {
    id
    name
    description
    category
    isPublic
    createdAt
    updatedAt
    createdBy {
      id
      email
      name
    }
    versions {
      id
      version
      content
      params
      inputSchema
      createdAt
      executions {
        id
        status
        latencyMs
        tokenIn
        tokenOut
        costUsd
      }
    }
  }
}
ParameterTypeDescription
id
required
ID!Unique identifier for the prompt

Response Structure

{
  "data": {
    "prompt": {
      "id": "cm1234567890",
      "name": "sentiment-analyzer",
      "description": "Analyzes sentiment of text with confidence scores",
      "category": "ANALYSIS",
      "isPublic": false,
      "createdAt": "2025-01-15T10:00:00Z",
      "updatedAt": "2025-01-20T14:30:00Z",
      "createdBy": {
        "id": "user_abc123",
        "email": "user@example.com",
        "name": "John Doe"
      },
      "versions": [
        {
          "id": "ver_xyz789",
          "version": 1,
          "content": "You are a sentiment analysis expert...",
          "params": {
            "model": "claude-3-5-sonnet-20241022",
            "temperature": 0.3,
            "max_tokens": 300
          },
          "inputSchema": {
            "type": "object",
            "properties": {
              "text": {
                "type": "string",
                "description": "Text to analyze"
              }
            },
            "required": ["text"]
          },
          "createdAt": "2025-01-15T10:00:00Z",
          "executions": []
        }
      ]
    }
  }
}

Mutations

Create Prompt

mutation
createPrompt

Create a new prompt (without versions)

mutation CreatePrompt($input: CreatePromptInput!) {
  createPrompt(input: $input) {
    id
    name
    description
    category
    isPublic
    createdAt
  }
}
ParameterTypeDescription
name
required
stringUnique name for the prompt (will be converted to kebab-case)
descriptionstringDescription of what the prompt does
categoryPromptCategoryCategory (GENERAL, SUMMARIZATION, ANALYSIS, etc.)
isPublicbooleanWhether the prompt is publicly visible (default: false)
Example Request
json
{
  "input": {
    "name": "sentiment-analyzer",
    "description": "Analyzes sentiment of text with confidence scores",
    "category": "ANALYSIS",
    "isPublic": false
  }
}

Create Prompt Version

mutation
createPromptVersion

Add a new version to an existing prompt

mutation CreatePromptVersion($input: CreatePromptVersionInput!) {
  createPromptVersion(input: $input) {
    id
    version
    content
    params
    inputSchema
    createdAt
  }
}
ParameterTypeDescription
promptId
required
ID!ID of the prompt to add version to
content
required
stringTemplate content with {{variables}}
params
required
JSONModel configuration (model, temperature, max_tokens)
inputSchemaJSONJSON Schema defining required inputs
Example Request
json
{
  "input": {
    "promptId": "cm1234567890",
    "content": "You are a sentiment analysis expert. Analyze: {{text}}\n\nFormat:\n- Sentiment: (Positive/Negative/Neutral)\n- Confidence: (0.0-1.0)",
    "params": {
      "model": "claude-3-5-sonnet-20241022",
      "temperature": 0.3,
      "max_tokens": 300
    },
    "inputSchema": {
      "type": "object",
      "properties": {
        "text": {
          "type": "string",
          "description": "Text to analyze"
        }
      },
      "required": ["text"]
    }
  }
}

Execute Prompt

mutation
executePrompt

Execute a prompt with provided inputs

mutation ExecutePrompt(
  $promptId: ID!
  $input: JSON!
  $version: Int
) {
  executePrompt(
    promptId: $promptId
    input: $input
    version: $version
  ) {
    output
    latencyMs
    tokenIn
    tokenOut
    costUsd
    executionId
    versionUsed
  }
}
ParameterTypeDescription
promptId
required
ID!ID of the prompt to execute
input
required
JSON!Input values matching the prompt's inputSchema
versionnumberSpecific version to execute (defaults to latest)
Example Request
json
{
  "promptId": "cm1234567890",
  "input": {
    "text": "I absolutely love this product! Best purchase ever!"
  }
}
Example Response
json
{
  "data": {
    "executePrompt": {
      "output": "- Sentiment: Positive\n- Confidence: 0.95",
      "latencyMs": 1250,
      "tokenIn": 45,
      "tokenOut": 28,
      "costUsd": "0.0012",
      "executionId": "exec_abc123",
      "versionUsed": 1
    }
  }
}

Update Prompt

mutation
updatePrompt

Update prompt metadata (name, description, category)

mutation UpdatePrompt(
  $id: ID!
  $input: UpdatePromptInput!
) {
  updatePrompt(id: $id, input: $input) {
    id
    name
    description
    category
    isPublic
    updatedAt
  }
}
ParameterTypeDescription
id
required
ID!ID of the prompt to update
namestringNew name for the prompt
descriptionstringNew description
categoryPromptCategoryNew category
isPublicbooleanUpdate public visibility

Fork Prompt

mutation
forkPrompt

Create a copy of a prompt with all its versions

mutation ForkPrompt($id: ID!) {
  forkPrompt(id: $id) {
    id
    name
    description
    category
    versions {
      id
      version
      content
      params
    }
  }
}
Forking creates a complete copy including all versions. The forked prompt will have a generated name like original-name-fork-abc123.

Delete Prompt

mutation
deletePrompt

Permanently delete a prompt and all its versions

mutation DeletePrompt($id: ID!) {
  deletePrompt(id: $id)
}
Deletion is permanent and cannot be undone. All versions and execution history will be lost.

Categories

Prompts can be categorized for better organization:

ParameterTypeDescription
GENERALPromptCategoryGeneral purpose prompts
SUMMARIZATIONPromptCategoryText summarization and condensation
ANALYSISPromptCategoryContent analysis and evaluation
GENERATIONPromptCategoryContent creation and generation
CLASSIFICATIONPromptCategoryCategorization and labeling
EXTRACTIONPromptCategoryData extraction and parsing
ROUTINGPromptCategoryIntent detection and routing
CUSTOMPromptCategoryCustom use cases

Error Handling

Common Errors

Authentication Error
json
{
  "errors": [
    {
      "message": "Unauthorized: Invalid API key",
      "extensions": {
        "code": "UNAUTHENTICATED"
      }
    }
  ]
}
Validation Error
json
{
  "errors": [
    {
      "message": "Input validation failed: missing required field 'text'",
      "extensions": {
        "code": "BAD_USER_INPUT",
        "field": "text"
      }
    }
  ]
}
Not Found Error
json
{
  "errors": [
    {
      "message": "Prompt not found with id: cm1234567890",
      "extensions": {
        "code": "NOT_FOUND"
      }
    }
  ]
}

Error Codes

ParameterTypeDescription
UNAUTHENTICATEDstringInvalid or missing API key
FORBIDDENstringInsufficient permissions to access resource
NOT_FOUNDstringResource does not exist
BAD_USER_INPUTstringInvalid input data or schema mismatch
INTERNAL_SERVER_ERRORstringUnexpected server error

Code Examples

JavaScript / TypeScript

Using fetch
typescript
const apiKey = 'your-api-key'
const endpoint = 'https://api.promptforge.sh/graphql'

async function executePrompt(promptId: string, input: any) {
  const response = await fetch(endpoint, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': apiKey,
    },
    body: JSON.stringify({
      query: `
        mutation ExecutePrompt($promptId: ID!, $input: JSON!) {
          executePrompt(promptId: $promptId, input: $input) {
            output
            latencyMs
            costUsd
          }
        }
      `,
      variables: {
        promptId,
        input,
      },
    }),
  })

  const { data, errors } = await response.json()

  if (errors) {
    throw new Error(errors[0].message)
  }

  return data.executePrompt
}

// Usage
const result = await executePrompt('cm1234567890', {
  text: 'This is amazing!',
})

console.log(result.output)
console.log(`Cost: $${result.costUsd}`)

Python

Using requests
python
import requests

api_key = 'your-api-key'
endpoint = 'https://api.promptforge.sh/graphql'

def execute_prompt(prompt_id: str, input_data: dict):
    query = """
        mutation ExecutePrompt($promptId: ID!, $input: JSON!) {
          executePrompt(promptId: $promptId, input: $input) {
            output
            latencyMs
            costUsd
          }
        }
    """

    response = requests.post(
        endpoint,
        headers={
            'Content-Type': 'application/json',
            'X-API-Key': api_key,
        },
        json={
            'query': query,
            'variables': {
                'promptId': prompt_id,
                'input': input_data,
            },
        },
    )

    result = response.json()

    if 'errors' in result:
        raise Exception(result['errors'][0]['message'])

    return result['data']['executePrompt']

# Usage
result = execute_prompt('cm1234567890', {
    'text': 'This is amazing!',
})

print(result['output'])
print(f"Cost: ${result['costUsd']}")

cURL

Execute Prompt
bash
curl -X POST https://api.promptforge.sh/graphql \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{
    "query": "mutation ExecutePrompt($promptId: ID!, $input: JSON!) { executePrompt(promptId: $promptId, input: $input) { output latencyMs costUsd } }",
    "variables": {
      "promptId": "cm1234567890",
      "input": {
        "text": "This is amazing!"
      }
    }
  }'

Best Practices

Version Control - Always create a new version when making significant changes to a prompt. This allows rollback and A/B testing.
Input Validation - Use comprehensive JSON Schema in inputSchema to validate inputs before execution. This prevents errors and wasted API calls.
Cost Monitoring - Track costUsd and token usage from execution responses to optimize spending.
Temperature Settings - Use lower temperature (0.0-0.3) for deterministic tasks like classification or extraction. Use higher values (0.7-1.0) for creative generation.
Rate Limits - Respect rate limits from AI providers. Implement exponential backoff and retry logic for production applications.

Next Steps

Chains API

Learn how to build multi-step workflows

Chains API →

Examples

See complete implementation examples

View Examples →